当左侧值与右侧值同名时,编写Golang结构的惯用方式是什么?示例:
type Something struct {
Names Names
}
type Names struct {
...
}
谢谢!
答案 0 :(得分:4)
将名称提供给与其类型名称相同的字段在Go中是完全有效的,并且经常使用。
标准库中的一些示例:
https://www.askdavetaylor.com/add-birthdays-apple-calendar/的字段:
URL *url.URL
Header Header
Response *Response
http.Request
的字段:
Handler Handler
http.Server
的字段:
CompressionLevel CompressionLevel
这不会引起混淆也不会造成歧义,因为引用结构变量的字段是varName.FieldName
(并且始终表示字段而不是其类型),而引用类型是declaringPackage.TypeName
。即使在同一程序包中声明了类型,也不一样(因此declaringPackage
是“ missing”),因为varName
不能为“ empty”。