我尝试了一下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)我做错了什么?
发布于 2018-12-16 04:25:06
当你在写的时候:
type Child struct {
p *Parent
}您并没有嵌入Parent,只是声明了一些*Parent类型的实例变量p。
要调用p方法,必须将调用转发给p
func (c *Child) Foo() {
c.p.Foo()
}通过嵌入,您可以避免这种记账,并且语法将是
type Child struct {
*Parent
}发布于 2018-12-16 04:08:41
你要么得打电话给
c.p.Foo()或者将Child struct更改为:
type Child struct {
*Parent
}https://stackoverflow.com/questions/53796786
复制相似问题