Anonymous Struct: Unveiling the Differences between struct{}{} and {}
In Go, declaring string-to-anonymous struct maps can be done in two ways:
<code class="go">var Foo = map[string]struct{}{ "foo": struct{}{}, }</code>
<code class="go">var Foo = map[string]struct{}{ "foo": {}, }</code>
While both expressions are valid, the second one raises a warning in Gogland regarding a "Redundant type declaration." To clarify, let's explore the underlying differences between these two forms.
Firstly, consider the following:
<code class="go">struct{}{}</code>
This is a composite literal consisting of the type (struct{}) and its value ({}). In contrast, this:
<code class="go">{}</code>
Is a composite literal that omits the type and retains only the value.
Ordinarily, composite literals require the inclusion of type specification to aid the compiler in identifying their intended type. As per the language specification:
CompositeLit = LiteralType LiteralValue .
However, when defining a map composite literal, the key and value types are already specified by the map type. Therefore, in cases where you plan to provide values of these specified types, type specification can be omitted.
This omission is sanctioned by the Go specification, which states:
"Within a composite literal of array, slice, or map type T, elements or map keys that are themselves composite literals may elide the respective literal type if it is identical to the element or key type of T."
In conclusion, the two expressions presented at the onset achieve the same end result. However, the latter leverages a language feature that allows the omission of redundant type specification in map composite literals.
The above is the detailed content of Anonymous Struct in Go: When is it Redundant to Specify the Type in `map[string]struct{}`?. For more information, please follow other related articles on the PHP Chinese website!