golang struct组合,转型问题请教
2024-09-08 17:28:21
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语言中文网
jarlyyn · #1 · 2年之前
是你自己在OnHurt里制定需要传入 Base啊……
能想到的做法有两个,一个是把base里的方法提取为一个interface
另一个版本就是做 base的Getter,比如 GetBase()*Base
然后加到action这个interface里面去。
最新文章
- CodeForces 520B Two Buttons
- understanding Nhibernate Hilo
- FiddlerScript修改特定请求参数下的返回值
- 各种python环境的问题
- 转:Windows Socket五种I/O模型
- scala的REPL shell的调用
- jps 显示process information unavailable解决方法
- Servlet常用类
- SQL Server-聚焦深入理解死锁以及避免死锁建议(三十三)
- 关于微信小程序图片失真的解决方案
- React Router 按需加载+服务器渲染的闪屏问题
- 12. ZooKeeper配额和认证
- [转] package-lock.json
- Android popupwindow 失去焦点或者点击空白区域时消失的解决方法
- IIS的地址指向
- Asp.net core中实现自动更新的Option
- face detection[Face R-CNN]
- 05Hadoop-左外连接
- rpm包安装的nginx热升级
- angular2项目关于Echarts图表的处理
热门文章
- Java : 对象不再使用时,为什么要赋值为 null ?
- HTML5游戏2D开发引擎
- Leet爬楼梯问题
- SQL 删除重复记录,只保留一条记录
- centos ntfs-3g not find
- 使用@ConfigurationProperties注解 提示 “Spring Boot Configuration Annotation Processor not found in classpath ”
- Android特定语言 Xtendroid
- java常用函数
- 【概率论】4-1:随机变量的期望(The Expectation of a Random Variable Part II)
- [转]vc中调用其他应用程序的方法(函数) winexec,shellexecute ,createprocess