gpt4 book ai didi

go - 理解 Go 中的接口(interface)

转载 作者:IT王子 更新时间:2023-10-29 02:27:58 26 4
gpt4 key购买 nike

我想了解接口(interface)在 Go 中是如何工作的。

假设我有 2 个结构:

package "Shape"

type Square struct {
edgesCount int
}

type Triangle struct {
edgesCount int
}

现在我创建一个 Shape 界面:

type Shape interface {

}

为什么我不能指定 Shape 接口(interface)有一个 egdesCount 属性?接口(interface)只应该重组方法吗?

我面临的另一个问题是共享功能。不可能想出这样的事情:

func New() *Shape {
s:=new(Shape)
s.edgesCount = 0
return s
}

这比必须重写完全相同的代码要好得多:

func New() *Square {
s:=new(Square)
s.edgesCount = 0
return s
}

func New() *Triangle {
s:=new(Triangle)
s.edgesCount = 0
return s
}

(这也带来了问题,因为我无法重新声明我的 New 函数...)

非常感谢您的帮助

最佳答案

您指的不是接口(interface)(它允许将对象作为该接口(interface)传递,仅仅是因为该对象是所有接口(interface)方法的接收者)。
在这里,一个 empty interface{}' Shape would be satisfied by any type ,这在这里没有用。

更多关于type embedding (例如使用 anonymous type structure):

这将提升公共(public)字段 edgesCount 到两个结构。
作为spec mentions :

A field or method f of an anonymous field in a struct x is called promoted if x.f is a legal selector that denotes that field or method f.

参见 this example :

type Shape struct {
edgesCount int
}

type Square struct {
Shape
}

type Triangle struct {
Shape
}

func NewSquare() *Square {
return &Square{
Shape{edgesCount: 4},
}
}
func NewTriangle() *Triangle {
return &Triangle{
Shape{edgesCount: 3},
}
}

func main() {
fmt.Printf("Square %+v\n", NewSquare())
fmt.Printf("Triangle %+v\n", NewTriangle())
}

输出:

Square &{Shape:{edgesCount:4}}
Triangle &{Shape:{edgesCount:3}}

关于go - 理解 Go 中的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28095956/

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