golang中没有继承的概念,不管是继承还是组合都是为了代码复用和模块化,golang通过组合实现代码的复用和模块化。以下面的例子可以看出组合的强大功能。
package main
import "fmt"
type Base struct {
val int
}
func (b *Base) Print() {
fmt.Println("hello, i am base")
}
type Child struct {
Base
}
func (c *Child) Print() {
fmt.Println("hello, i am child")
}
func main() {
b := &Base{}
b.Print()
c := &Child{}
c.Print()
c.Base.Print()
}
以组合的思路来看,上面代码运行结果不出所料:
hello, i am base
hello, i am child
hello, i am base