【发布时间】:2016-06-30 13:00:37
【问题描述】:
我有以下几点:
type Base struct {
}
func(base *Base) Get() string {
return "base"
}
func(base *Base) GetName() string {
return base.Get()
}
我想用新的 Get() 实现定义一个新类型,这样我就可以使用新类型代替 Base 并且在调用 GetName() 的地方调用新的 Get() 实现。如果我使用 Java,我将继承 Base 并覆盖 Get()。我应该如何在 Go 中实现这一点?如果可能,我想避免破坏性更改,因此不需要更改 Base 的现有使用者。
我的第一次尝试看起来像......
type Sub struct {
Base
}
func(sub *Sub) Get() string {
return "Sub"
}
..这不起作用。我的大脑还没有完全适应 Go。
【问题讨论】:
-
Go 没有继承,也没有泛型。如果某些东西需要
Base类型,则不能提供其他类型。 -
我想向您推荐this post。
标签: inheritance go overriding