先来看看组合的示例代码:
package main
import (
"fmt"
)
type Base struct {
// nothing
}
func (b *Base) ShowA() {
fmt.Println("showA")
b.ShowB()
}
func (b *Base) ShowB() {
fmt.Println("showB")
}
type Derived struct {
Base
}
func (d *Derived) ShowB() {
fmt.Println("Derived showB")
}
func main() {
d := Derived{}
d.ShowA()
}
上述代码执行结果不会输出“Derived showB”,因为Go中没有继承的概念,只有组合,上面的Derived包含了Base,自动的含有了Base的方法,因为其不是继承,所以不会根据具体传入的对象而执行对应的方法。
go通过结构嵌入实现自动的转发方法。例如将Base嵌入Derived中,不给定字段名。d.ShowA()