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

标签 go

我想了解接口(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/

相关文章:

debugging - 如何使用 BPF (BCC) 跟踪 go 函数

去imap : bad sequence set value ""

Go 工具无法找到二进制文件。去工具: no such tool "vet"

go - 无效类型断言 : cannot convert os. 接口(interface)类型 io.ReadWriter 的标准输出?

json - 将结构转换为 JSON,其中一个字段是另一个结构

golang 迷失在倒影中

windows - 无法使用protoc-gen-go构建protobuf

go - GO 结构定义中的字符串文字

google-app-engine - 仅对我的一个模块有很长的延迟

git - 如何指定 `go get` 将使用哪个 ssh key