golang继承与多态


golang中的继承

package main

import "log"

type Person struct {
	Name string
	Age  int
}
type Student struct {
	Person
	Student int
}

func (p Person) SayHello() {
	log.Printf("[Person.SayHello][name:%v][age:%v]", p.Name, p.Age)
}
func main() {
	p1 := Person{
		Name: "大头儿子",
		Age:  10,
	}
	s1 := Student{
		Person:  p1,
		Student: 1000,
	}

	s1.SayHello()
}

直接调用结构体绑定的方法

package main

import "log"

type user struct {
	name  string
	email string
}
type admin struct {
	name string
	age  int
}

func (u *user) notify() {
	log.Printf("[普通用户的通知][notify to user :%s]", u.name)
}
func (u *admin) notify() {
	log.Printf("[管理员的通知][notify to user :%s]", u.name)
}

func main() {
	//
	u1 := user{
		name:  "大头儿子",
		email: "xy@qq.com",
	}
	a1 := admin{
		name: "小头爸爸",
		age:  18,
	}
	log.Println("直接调用结构体绑定的方法")
	u1.notify()
	a1.notify()
}

多态

package main

import "log"

type notifer interface {
	notify()
}

type user struct {
	name  string
	email string
}
type admin struct {
	name string
	age  int
}

func (u *user) notify() {
	log.Printf("[普通用户的通知][notify to user :%s]", u.name)
}
func (u *admin) notify() {
	log.Printf("[管理员的通知][notify to user :%s]", u.name)
}

func sendNotify(n notifer) {
	n.notify()
}
func main() {
	//
	u1 := user{
		name:  "大头儿子",
		email: "xy@qq.com",
	}
	a1 := admin{
		name: "小头爸爸",
		age:  18,
	}
	// 体现多态
	log.Println("体现多态")
	sendNotify(&u1)
	sendNotify(&a1)
}

灵魂承载

package main

import (
	"log"
)

type notifer interface {
	notify()
}

type user struct {
	name  string
	email string
}
type admin struct {
	name string
	age  int
}

func (u *user) notify() {
	log.Printf("[普通用户的通知][notify to user :%s]", u.name)
}
func (u *admin) notify() {
	log.Printf("[管理员的通知][notify to user :%s]", u.name)
}

func sendNotify(n notifer) {
	n.notify()
}
func main() {
	//
	u1 := user{
		name:  "大头儿子",
		email: "xy@qq.com",
	}
	a1 := admin{
		name: "小头爸爸",
		age:  18,
	}
	//log.Println("直接调用结构体绑定的方法")
	//u1.notify()
	//a1.notify()
	// 体现多态
	log.Println("体现多态")
	sendNotify(&u1)
	sendNotify(&a1)
	//灵魂
	log.Println("多态灵魂承载容器")
	ns := make([]notifer, 0)
	ns = append(ns, &u1)
	ns = append(ns, &a1)
	for _, n := range ns {
		n.notify()
	}
}

Author: 千里
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source 千里 !
  TOC