亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go 嵌入:方法未繼承

Go 嵌入:方法未繼承

Go
眼眸繁星 2023-05-15 15:40:19
我正在嘗試 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)我做錯了什么?
查看完整描述

2 回答

?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

當你寫作時:


type Child struct {

    p *Parent

}

你沒有嵌入Parent,你只是聲明了一些類型p的實例變量*Parent。


要調用p方法,您必須將調用轉發到p


func (c *Child) Foo() {

    c.p.Foo()

}

通過嵌入你可以避免這種簿記,語法將是


type Child struct {

    *Parent

}


查看完整回答
反對 回復 2023-05-15
?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

你要么必須打電話

c.p.Foo()

或將 Child 結構更改為此:

type Child struct {
    *Parent
}


查看完整回答
反對 回復 2023-05-15
  • 2 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號