我正在嘗試 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)我做錯(cuò)了什么?
2 回答

不負(fù)相思意
TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
當(dāng)你寫作時(shí):
type Child struct {
p *Parent
}
你沒有嵌入Parent,你只是聲明了一些類型p的實(shí)例變量*Parent。
要調(diào)用p方法,您必須將調(diào)用轉(zhuǎn)發(fā)到p
func (c *Child) Foo() {
c.p.Foo()
}
通過嵌入你可以避免這種簿記,語法將是
type Child struct {
*Parent
}

繁星淼淼
TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超11個(gè)贊
你要么必須打電話
c.p.Foo()
或?qū)?Child 結(jié)構(gòu)更改為此:
type Child struct { *Parent }
- 2 回答
- 0 關(guān)注
- 133 瀏覽
添加回答
舉報(bào)
0/150
提交
取消