内容简介:实现思路:直接上代码:
实现思路:
父类方法接收子类对象,通过 反射
调用子类方法
直接上代码:
package main import ( "fmt" "reflect" ) type A struct { } func (self A) say() { println(self.Name()) } func (self A) sayReal(child interface{}) { ref := reflect.ValueOf(child) method := ref.MethodByName("Name") if (method.IsValid()) { r := method.Call(make([]reflect.Value, 0)) fmt.Println(r[0].String()) } else { // 错误处理 } } func (self A) Name() string { return "I'm A" } type B struct { A } func (self B) Name() string { return "I'm B" } type C struct { A } func main() { b := B{} b.say() //I'm A b.sayReal(b) //I'm B c := C{} c.say() //I'm A b.sayReal(b) //I'm A }
以上所述就是小编给大家介绍的《golang 父类调用子类方法、继承多态的实现方式》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 从python中的父类文件调用子类方法
- python – 如何子类化大pandasDataFrame?
- 父类返回子类类型的函数写法
- ios – 在哪里为子类的uitableviewcell创建自动布局约束?
- C#中子类对基类方法的继承、重写和隐藏
- 如何用 SQL 中的循环查询无限级分类的所有子类
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Don't Make Me Think
Steve Krug / New Riders Press / 18 August, 2005 / $35.00
Five years and more than 100,000 copies after it was first published, it's hard to imagine anyone working in Web design who hasn't read Steve Krug's "instant classic" on Web usability, but people are ......一起来看看 《Don't Make Me Think》 这本书的介绍吧!
随机密码生成器
多种字符组合密码
RGB CMYK 转换工具
RGB CMYK 互转工具