英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论