首页 > 其他 > 详细

golang struct组合,转型问题请教

时间:2019-10-31 23:05:12      阅读:135      评论:0      收藏:0      [点我收藏+]
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语言中文网技术分享图片

534 次点击  
加入收藏 微博 
 
3 回复  |  直到 2018-03-19 09:56:41
技术分享图片
jarlyyn · #1 · 2年之前

是你自己在OnHurt里制定需要传入 Base啊……

能想到的做法有两个,一个是把base里的方法提取为一个interface

另一个版本就是做 base的Getter,比如 GetBase()*Base

然后加到action这个interface里面去。

技术分享图片
zhjzjnb · #2 · 2年之前
对 技术分享图片jarlyyn #1 回复

我是想以多态的方式编写代码,所以OnHurt参数是base,go继承采用组合和非入侵,还是和java,c++有所不同

技术分享图片
jarlyyn · #3 · 2年之前
对 技术分享图片zhjzjnb #2 回复

写golang的程序要忘记那些。

最基本的一点,golang不是传统的oop的

golang struct组合,转型问题请教

原文:https://www.cnblogs.com/ExMan/p/11773865.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!