我有以下内容:
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"
}
..这是行不通的。我的大脑还没有完全适应围棋。
最佳答案
接口(interface)是方法签名的命名集合:
参见:https://gobyexample.com/interfaces
和:http://www.golangbootcamp.com/book/interfaces
所以最好不要以这种面向对象的方式使用。
你问的不是 Golang 惯用语 但可能(2 种方式):
这就是您所需要的(工作示例代码):
package main
import "fmt"
type Base struct {
}
func (base *Base) Get() string {
return "base"
}
type Getter interface {
Get() string
}
func (base *Base) GetName(getter Getter) string {
if g, ok := getter.(Getter); ok {
return g.Get()
} else {
return base.Get()
}
}
// user code :
type Sub struct {
Base
}
func (t *Sub) Get() string {
return "Sub"
}
func (t *Sub) GetName() string {
return t.Base.GetName(t)
}
func main() {
userType := Sub{}
fmt.Println(userType.GetName()) // user string
}
输出:
Sub
如您所见,必须在用户代码中完成一个初始化代码:
func (t *Sub) GetName() string {
return t.Base.GetName(t)
}
这也行:
package main
import "fmt"
type Getter interface {
Get() string
}
type Base struct {
Getter
}
func (base *Base) Get() string {
return "base"
}
func (base *Base) GetName() string {
return base.Getter.Get()
}
// user code :
type Sub struct {
Base
}
func (t *Sub) Get() string {
return "Sub"
}
func New() *Sub {
userType := &Sub{}
userType.Getter = interface{}(userType).(Getter)
return userType
}
func main() {
userType := New()
fmt.Println(userType.GetName()) // user string
}
输出:
Sub
如您所见,必须在用户代码中完成一个初始化代码:
userType.Getter = interface{}(userType).(Getter)
关于inheritance - Golang 方法覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38123911/