interface - Go:从嵌入式结构覆盖接口(interface)方法

标签 interface go overriding

考虑以下代码:

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() 的方法吗>TypeB 的实例在 TypeB 的嵌入式 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/

相关文章:

c# - 覆盖子类中的通用 IEnumerable 接口(interface)

c# - Entity Framework 代码优先 - 接口(interface)

java - 在 java 中重写父类(super class)的父类(super class)中的方法?

google-app-engine - 使用 Cloud Datastore 初始化 Go AppEngine 应用

json - 去解码reflect.Type得到map[string]interface{}

module - 在 prestashop 中卸载模块时如何删除覆盖?

html - 文本叠加背景颜色 rgba

interface - SAP .NET 连接器 : System exception thrown while marshaling . NET 类型

java - 接口(interface)和实现方法

go - 我如何使用 exec.Command().Output() 返回相同类型的值