Anonymous Struct: Unveiling the Differences between struct{}{} and {}
In Go, declaring string-to-anonymous struct maps can be done in two ways:
var Foo = map[string]struct{}{
"foo": struct{}{},
}
var Foo = map[string]struct{}{
"foo": {},
}
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:
struct{}{}
This is a composite literal consisting of the type (struct{}) and its value ({}). In contrast, this:
{}
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3