封装

  • 封装的私有直接使用的是大小写来判断,关键字都不需要
type Dog struct{
	name string
}
func (d Dog) Say() {
	fmt.Println("woof")
}

继承(嵌入)

type animal struct {
    Name string
}
type Dog struct {
    *animal
}
  • 嵌入容易产生屏蔽问题

多态

type Animal interface {
    Name() string
    Speak() string
    Play()
}

type Dog struct {
    name string
    gender string
}

func (d *Dog) Play() {
    fmt.Println(d.Speak())
}

func (d *Dog) Speak() string {
    return fmt.Sprintf("my name is %v and my gender is %v", d.name, d.gender)
}

func (d *Dog) Name() string {
    return d.name
}

func Play(a Animal) {
    a.Play()
}

参考

https://zhuanlan.zhihu.com/p/165621566 https://www.cnblogs.com/apocelipes/p/14090671.html https://www.cnblogs.com/u-vitamin/p/10793554.html https://www.cnblogs.com/dogtwo0214/p/13419080.html