假設我有個PersonstructtypePersonstruct{}typeManstruct{Person}typeHumanstruct{Person}現在我想要一個函數p(aPerson)參數是Person類型,然后我想定義一個Man跟Human實例,可以調用p這個方法,請問怎么實現呢
2 回答

30秒到達戰場
TA貢獻1828條經驗 獲得超6個贊
可以先定義和接口,然后man和human去實現這個接口typePersonstruct{}typePinterface{p(aPerson)}typeManstruct{}func(m*Man)p(aPerson){}typeHumanstruct{}func(m*Human)p(aPerson){}實現接口的這種方式,當一個有一個函數參數是P時,傳的參可以是Man,也可以是Human,通過實現同一個接口實現多態funcperson(pP){}如果只是單純的想要給struct添加方法,下面就可以typeManstruct{}func(m*Man)p(aPerson){}typeHumanstruct{}func(m*Human)p(aPerson){}

眼眸繁星
TA貢獻1873條經驗 獲得超9個贊
接口方式如果不是題主想要的話,可以嘗試如下typePersonstruct{}typeManstruct{Person}typeHumanstruct{Person}funcp(aPerson){fmt.Println("inp")}m:=Man{Person{}}p(m.Person)