在以下代码中,我展示了我认为在golang中嵌入(方法被提升)和组合(方法不被提升)之间的区别。
为什么你会想要在golang中使用组合?
type obj1Inherited struct {
obj2
}
type obj1Composed struct {
someobj obj2
}
type obj2 struct {
}
func (o obj2) printTest() {
fmt.Println("obj2")
}
func main() {
o := obj1Inherited{}
o.printTest() //fine - printTest is promoted
obj1Composed := obj1Composed{}
obj1Composed.someobj.printTest() //fine because I'm using the composed obj
obj1Composed.printTest() //not fine - printTest is NOT promoted