在下面的代码中,我展示了我认为在 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
慕侠2389804
精慕HU
慕容708150
相关分类