请教一下golang 中如何实现 override

zjcxc 2021-03-18 09:10:17

package main

import "fmt"

type IInfo interface {
GetName() string
GetInfo() string
}

type a struct {
Name string
}

func (this *a) GetName() string {
return "a is " + this.Name
}

func (this *a) GetInfo() string {
return this.GetName()
}

type b struct {
a
}

// 重写一下该方法
func (this *b) GetName() string {
return "b is " + this.Name
}

func main() {
a := a{Name: "dog"}
fmt.Printf("a.GetName: %s\n", a.GetName())
fmt.Printf("a.GetInfo: %s\n", a.GetInfo())
b := b{a}
//输出 b.GetName: b is dog,说明是调用了重写后的方法
fmt.Printf("b.GetName: %s\n", b.GetName())
//输出 b.GetInfo: a is dog,说明是调用的是a的方法,希望得到的结果是调用重写后的方法
fmt.Printf("b.GetInfo: %s\n", b.GetInfo())
}
...全文
836 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_29817615 2021-11-02
  • 打赏
  • 举报
回复

golang没有继承,就没有基类的概念,也就没有重写。

梦回水乡 2021-04-12
  • 打赏
  • 举报
回复
实现 IInfo 的所有方法就行。
鸭绿江小舟 2021-04-09
  • 打赏
  • 举报
回复
package main import "fmt" type IInfo interface { GetName() string GetInfo() string } type a struct { ThisObj IInfo Name string } func (this *a) GetName() string { return "a is " + this.Name } func (this *a) GetInfo() string { return this.ThisObj.GetName() } type b struct { a } // 重写一下该方法 func (this *b) GetName() string { return "b is " + this.Name } func main() { a := a{Name: "dog"} a.ThisInfo = &a fmt.Printf("a.GetName: %s\n", a.GetName()) fmt.Printf("a.GetInfo: %s\n", a.GetInfo()) b := b{a} b.ThisInfo =&b //输出 b.GetName: b is dog,说明是调用了重写后的方法 fmt.Printf("b.GetName: %s\n", b.GetName()) //输出 b.GetInfo: a is dog,说明是调用的是a的方法,希望得到的结果是调用重写后的方法 fmt.Printf("b.GetInfo: %s\n", b.GetInfo()) } 习惯了面向对象的语言转向Go都会有楼主的不习惯,我是通过在基类设置ThisObj的成员绕过去的,ThisObj总是指向派生类对象,管用
「已注销」 2021-03-25
  • 打赏
  • 举报
回复
go语言没有override的语义。也就没有如c++在内部实现一个虚拟方法表。建议不强扭着实现。go提倡组合而非继承。
qybao 2021-03-25
  • 打赏
  • 举报
回复
引用 3 楼 zjcxc--个人微信公共号同名 的回复:
简单地说 a 是基础类,实现了两个方法 现在基于a(继承)实现一个b类,b类只有一个方法与a不一样,所以只需要把这个不一样的方法重写一下(overide) 如果在 b 中把所有方法重写一遍,那就是不继承,是完全重写了 对象编程都是这么玩的嘛
go本身没有继承,而是用组合模拟继承的,所以做不到 以前回答过类似的问题,可以参考以下链接 https://bbs.csdn.net/topics/397945851
zjcxc 2021-03-18
  • 打赏
  • 举报
回复
简单地说 a 是基础类,实现了两个方法 现在基于a(继承)实现一个b类,b类只有一个方法与a不一样,所以只需要把这个不一样的方法重写一下(overide) 如果在 b 中把所有方法重写一遍,那就是不继承,是完全重写了 对象编程都是这么玩的嘛
ying1234 2021-03-18
  • 打赏
  • 举报
回复
什么意思?你GetInfo方法只在a里定义了,b里又没有定义,当然是调用a里的GetInfo方法了,你在b里重写一下不就行了。

2,348

社区成员

发帖
与我相关
我的任务
社区描述
go语言学习与交流版
社区管理员
  • go语言社区
  • 俺叫西西弗斯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧