go语言结构体没有继承的概念,但可以通过结构体组合的方式,实现类似于继承的效果。
如下:
type Animal struct {
Name string
Sound string
}
func (an *Animal) SetSound(sound string) {
an.Sound = sound
}
type Cat struct {
Animal
}
type Dog struct {
a Animal
}
func TestOther(t *testing.T) {
cat := Cat{}
cat.Name = "cat"
cat.SetSound("miao")
t.Log(cat)
dog := Dog{}
dog.a.Name = "dog"
dog.a.SetSound("wang")
t.Log(dog)
}
结果输出:

可以看到,以上两种操作方式的结果是一致的,但是通过隐式指定的方式,原结构体Animal的字段和方法就像是被“继承”到结构体Cat里一样。
cat可以直接调用Animal结构体中的Name等字段以及SetSound方法,就像是Cat结构的原生字段和方法一样。


