What is the idiomatic way to write a Golang struct when the left side value is has the same name as the right side value? Example:
type Something struct {
Names Names
}
type Names struct {
...
}
Thanks!
Giving the name to a field that is identical to its type name is perfectly valid in Go, and is often used.
Some examples from the standard library:
Fields of http.Request
:
URL *url.URL
Header Header
Response *Response
Fields of http.Server
:
Handler Handler
Fields of png.Encoder
:
CompressionLevel CompressionLevel
This doesn't cause confusion nor ambiguity, because referring to a struct variable's fields is varName.FieldName
(and this always denotes the field and not its type), and referring to the type is declaringPackage.TypeName
. It's not the same even if the type is declared in the same package (and hence declaringPackage
is "missing"), because varName
cannot be "empty".