考虑以下代码:
type Intf interface {
Method()
}
type TypeA struct {
TypeBInst Intf
}
func (*TypeA) Method() {
log.Println("TypeA's Method")
}
func (t *TypeA) Specific() {
t.TypeBInst.Method() // Call override from TypeB
log.Println("Specific method of TypeA")
}
type TypeB struct {
*TypeA
}
func (*TypeB) Method() {
log.Println("TypeB's Method")
}
除了存储指向 的指针之外,还有另一种从
的实例在 func (t *TypeA) Specific()
内部调用 func (*TypeB) Method()
的方法吗>TypeBTypeB
的嵌入式 TypeA
实例中?是否违反golang原则?
工作示例:playground
最佳答案
Is there another way to call func (*TypeB) Method() from inside func (t *TypeA) Specific() than storing a pointer to a TypeB's instance inside the embedded TypeA instance of TypeB?
是的,there is :
package main
import "log"
type TypeB struct{}
func (*TypeB) Method() {
log.Println("TypeB's Method")
}
func main() {
(*TypeB).Method(nil)
}
但它只适用于 nilable 接收器(不需要接收器的实例)。
Is it against golang principles?
据我所知,我个人从来没有在任何项目中需要这个。
关于interface - Go:从嵌入式结构覆盖接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30399963/