关于go:struct第一行只是一个接口,它是什么意思?


struct first line is just an interface, what does it mean?

本问题已经有最佳答案,请猛点这里访问。

我在Go中遇到了以下代码:

1
2
3
4
5
6
type Mytype struct {
  Interfacename
  var1  ClientInterface1
  var2  ClientInterface2
  id    int
}

第一个字段是什么意思?


通常,这就是在进行过程中如何实现某种继承(通过组合而不是继承)的方式。 检查一下:https://golang.org/doc/effective_go.html#embedding

这将授予外部类型(MyType)访问此内部类型的Receiver方法的权限(已分配的struct {},因为这是一个接口)。

从有效开始:

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

谢谢@Flimzy和@ md2perpe

另外,它定义了一个匿名字段,其变量名将与其类型名相同。