golang struct組合,轉型問題請教

type Action interface { OnHurt2(other Action) GetDamage() int } type Base struct { atk, hp int } func (this *Base) OnHurt(other *Base) { this.hp -= other.atk } func (this *Base) OnHurt2(other Action) { this.hp -= other.GetDamage() } func (this *Base) GetDamage() int { return 100 } type Child struct { Base } c1 := &Child{Base{atk: 20, hp: 100}} c2 := &Child{Base{atk: 40, hp: 60}} //這裏報錯cannot use type *Child to type *Base c1.OnHurt(c1) //要顯示指定Base,有沒有辦法不顯示指定 c1.OnHurt(&c2.Base) //用一個接口來轉型,可是這樣的話一個接口會很臃腫。 //有沒有好辦法,幫忙改造下 c1.OnHurt2(c2) 

入羣交流(和以上內容無關):Go中文網 QQ 交流羣:729884609 或加微信入微信羣:274768166 備註:入羣;關注公衆號:Go語言中文網java

534 次點擊  
加入收藏  微博 
 
3 回覆  |  直到 2018-03-19 09:56:41
jarlyyn
jarlyyn · #1 · 2年以前

是你本身在OnHurt裏制定須要傳入 Base啊……c++

能想到的作法有兩個,一個是把base裏的方法提取爲一個interfacegolang

另外一個版本就是作 base的Getter,好比 GetBase()*Base微信

而後加到action這個interface裏面去。markdown

zhjzjnb
zhjzjnb · #2 · 2年以前
對  jarlyynjarlyyn  #1 回覆

我是想以多態的方式編寫代碼,因此OnHurt參數是base,go繼承採用組合和非入侵,仍是和java,c++有所不一樣ide

jarlyyn
jarlyyn · #3 · 2年以前
對  zhjzjnbzhjzjnb  #2 回覆

寫golang的程序要忘記那些。oop

最基本的一點,golang不是傳統的oop的ui

相關文章
相關標籤/搜索