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语言中文网