gpt4 book ai didi

go - GoLang 对由结构和嵌入式结构实现的接口(interface)的类型转换是如何工作的

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

我最近发现一段代码在做一些我不理解的事情。

有多个结构具有相同的嵌入式结构和一个接口(interface),该接口(interface)定义返回指向每个结构的指针的方法。此接口(interface)由嵌入式结构实现,但仅“部分”由各个结构实现,因此,每个结构仅实现返回指向该结构的指针的方法。

为了更好的理解,这里有代表性的代码:

type BarStocks interface {
GetVodka() *Vodka
GetMartini() *Martini
GetBourbon() *Bourbon
GetNegroni() *Negroni
GetManhattan() *Manhattan
}

type BaseAttributes struct {
ID uuid.UUID
Quantity float64
CreatedAt time.Time
UpdatedAt time.Time
}

func (e *BaseAttributes) GetVodka() *Vodka {
return nil
}

func (e *BaseAttributes) GetMartini() *Martini {
return nil
}

func (e *BaseAttributes) GetBourbon() *Bourbon {
return nil
}

func (e *BaseAttributes) GetNegroni() *Negroni {
return nil
}

func (e *BaseAttributes) GetManhattan() *Manhattan {
return nil
}

然后每个单独的结构只实现返回其指针的方法,例如:

type Vodka struct {
BaseAttributes

Label string
}

func (v *Vodka) GetVodka() *Vodka {
return v
}

现在在代码中,此设置用于将单个结构作为指针类型转换为接口(interface),如下所示:

func someFunc() BarStocks {
v := Vodka{}
return &v
}

现在我对 Go 还不是很深入,所以无法理解指向结构的指针如何变成与接口(interface)相同的类型。

在此先感谢您对此的任何见解。

最佳答案

我会尽力回答您提出的问题。

documentation关于嵌入解释了您所看到的行为,

There's an important way in which embedding differs from subclassing. When we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one.

这解释了 Vodka 结构,它嵌入了结构 BaseAttributes,它实现了 BarStocks 中的所有方法,能够满足接口(interface) 棒材。然而,这段摘录并没有解释我们如何有效地为我们的 Vodka 结构覆盖 GetVodka()

要理解这一点,我们需要阅读文档中的另一段摘录。

Embedding types introduces the problem of name conflicts but the rules to resolve them are simple. First, a field or method X hides any other item X in a more deeply nested part of the type.

这段摘录解释了如果 Vodka 实现了 GetVodka() 并嵌入了一个结构 (BaseAttributes),它也实现了 GetVodka() ,最外层的定义优先。

这些行为的组合解释了 Vodka 如何满足 BarStocks 接口(interface)并具有您在示例代码中看到的行为。

关于go - GoLang 对由结构和嵌入式结构实现的接口(interface)的类型转换是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49962698/

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