第一行的结构只是一个接口,这是什么意思?

huangapple go评论74阅读模式
英文:

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

问题

第一个字段"Interfacename"是一个类型,它被嵌入到了结构体"Mytype"中。在Go语言中,嵌入类型可以通过结构体的字段名来访问其内部的字段和方法。这种方式可以实现类似继承的效果,使得结构体可以继承嵌入类型的字段和方法。

英文:

I come across this code in Go:

type Mytype struct {
  Interfacename
  var1  ClientInterface1
  var2  ClientInterface2
  id    int
}

What does that first field mean?

答案1

得分: 2

大多数情况下,通过组合而不是继承来实现某种继承的方式是在Go语言中实现的。请查看这个链接:https://golang.org/doc/effective_go.html#embedding

这将使外部类型(MyType)能够访问内部类型的接收器方法(分配的struct{},因为这是一个接口)。

根据《Go Effective》的说明:

嵌入与子类化有一个重要的区别。
当我们嵌入一个类型时,该类型的方法成为外部类型的方法,但当调用这些方法时,方法的接收器是内部类型,而不是外部类型。

感谢**@Flimzy@md2perpe**的贡献。

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

英文:

Mostly, this is how some sort of inheritance (by composition rather than inheritance) is achieved in go. Check this out: https://golang.org/doc/effective_go.html#embedding

This will grant the Outer type (MyType) access to this inner type's Receiver methods (the assigned struct{} since this is an interface).

From Go Effective:
> 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

Thanks @Flimzy and @md2perpe

Also, this defines an anonymous field, for which the variable name will be the same as its type name.

huangapple
  • 本文由 发表于 2017年4月8日 08:46:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/43289001.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定