我正在尝试 golang 嵌入,但以下代码无法编译:
type Parent struct {}
func (p *Parent) Foo() {
}
type Child struct {
p *Parent
}
func main() {
var c Child
c.Foo()
}
与
./tmp2.go:18:3: c.Foo undefined (type Child has no field or method Foo)
我做错了什么?
最佳答案
写作时:
type Child struct {
p *Parent
}
您没有嵌入Parent
,您只是声明了一些 *Parent
类型的实例变量 p
。
要调用 p
方法,您必须将调用转发给 p
func (c *Child) Foo() {
c.p.Foo()
}
通过嵌入你可以避免这种簿记,语法将是
type Child struct {
*Parent
}
关于去嵌入 : method not inherited,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53796786/