gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:28:34 26 4
gpt4 key购买 nike

考虑以下代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com