anonymous fields in type declaration?

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

anonymous fields in type declaration?

问题

我遇到了这个类型声明:

type Handler func(*Conn)

type Server struct {
  Handshake func(*Config, *http.Request) error
  Handler
}

(这是https://github.com/golang/net/blob/38c17adf51120973d1735785a7c02f8ce8297c5e/websocket/server.go#L55-L66的简化版本)

Server 结构体中的第二个字段是匿名的。只有类型,没有名称。

这是类型声明的语法(https://golang.org/ref/spec#Type_declarations):

TypeDecl     = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
TypeSpec     = identifier Type .

它明确要求一个标识符名称。但是我引用的那个包含语法的部分也提到了匿名字段。

我不明白为什么这种语法是正确的,以及如何使用匿名字段。

英文:

I came across this type declaration:

type Handler func(*Conn)

type Server struct {
  Handshake func(*Config, *http.Request) error
  Handler
}

(this is a simplified version of https://github.com/golang/net/blob/38c17adf51120973d1735785a7c02f8ce8297c5e/websocket/server.go#L55-L66

The second field in the Server structure is anonymous. There is just type and no name.

Here is the grammar for type declarations (https://golang.org/ref/spec#Type_declarations):

TypeDecl     = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
TypeSpec     = identifier Type .

and it clearly requires an identifier name. But yet the section that I referenced that contains the grammar, also mentions anonymous fields.

I do not understand why this syntax is correct and how anonymous fields are used.

答案1

得分: 2

你想查看与结构有关的语法部分,而不仅仅是类型。请参考:结构类型AnonymousField的使用。仅查看TypeSpec的产生式会将注意力集中在错误的地方。相反,应该查看FieldDecl;语法表明我们有两种可能性:命名字段(IdentifierList Type)或匿名字段(AnonymousField)。

匿名字段通常用于嵌入。在你的示例中,Server会像Handler一样运行,因为它嵌入了该字段。

英文:

You want to look at the part of the grammar that has to do with structures, not just types. See: Struct types and the use of AnonymousField. Looking just at the production for TypeSpec is focusing attention on the wrong place. Instead, look at FieldDecl; the grammar shows that we have two possibilities: named fields (IdentifierList Type), or anonymous fields (AnonymousField).

Anonymous fields are typically used for embedding. In your example, a Server will act like a Handler because it has embedded that field.

huangapple
  • 本文由 发表于 2015年1月17日 06:51:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/27994050.html
匿名

发表评论

匿名网友

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

确定