在Go中调用嵌入式类型的重载方法的正确方法 [英] Proper way to call overloaded method of embedded type in Go
问题描述
我有一个界面:
package pkg
type BaseInterface interface {
func Nifty() bool
func Other1()
func Other2()
...
func Other34123()
}
和实现它的结构:
package pkg
type Impl struct {}
func (Impl) Nifty() bool { ... }
然后是另一个结构,该结构要嵌入第一个结构并自己做Nifty():
Then along comes another struct which wants to embed the first and do it's own Nifty():
package myOtherPackage
import "pkg"
type ImplToo struct {
*pkg.Impl
}
func (it ImplToo) Nifty() bool { ... something else ... }
这有点像类继承,在OOP语言中有方法重写.我想知道如何做相当于implToo.super().Nifty()的方法-也就是说,从ImplToo Nifty()实现中,调用pkg.Impl Nifty()实现.
This is sort of like class inheretance with method override in an OOP language. I want to know how to do the equivalent of implToo.super().Nifty() - that is, from the ImplToo Nifty() implementation, call the pkg.Impl Nifty() implementation.
要在 it
上使用的正确转换是什么,以便我可以完成此转换?我尝试的所有操作都会对ImplToo的Nifty()产生无限制的递归,或者会产生一些编译器错误,例如:
What is the proper conversion to use on it
so that I can accomplish this? Everything I try yields either unbounded recursion on ImplToo's Nifty(), or some compiler error such as:
无效的类型断言:(& it).(BaseInterface)(非接口类型,*它在左侧)
...或对此有很多变化.
... or many variations on that.
推荐答案
您在寻找;
type ImplToo struct {
pkg.Impl
}
func (it ImplToo) Nifty() bool { return it.Impl.Nifty() }
您使用的指针不一致,可能是问题的一部分(不是肯定的).如果要使嵌入式类型成为指针,则使您的方法也使接收类型成为指针,以免发生此问题.
Your use of pointers isn't consistent which is probably (not positive) part of your problem. If you want to make the embedded type a pointer then make your methods receiving type a pointer as well to avoid this problem.
如果要在嵌入式类型中显式使用方法,则可以使用通常具有属性名称的类型来引用该方法.
If you want to explicitly use a method in the embedded type you reference it using the type where you would normally have a property name.
这篇关于在Go中调用嵌入式类型的重载方法的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!