Home > Article > Backend Development > Anonymous Structs in Go: When to Use `struct{}{} vs. {}`?
In Go, maps can associate strings with custom anonymous structs. The declaration of such a map may trigger a "Redundant type declaration" warning in IDEs like Gogland. This raises the question of the difference between struct{}{} and {} declarations.
Syntax Explanation
The struct{}{} syntax represents a composite literal that includes both the type (struct{}) and the value ({}). On the other hand, {} is also a composite literal, but it omits the type.
Compiler Implications
In general, composite literals require the type to be specified. However, when declaring maps, the types of the key and value are inferred from the map type. Therefore, you can omit the type when assigning composite literal values if they match these inferred types.
This exception was introduced in Go 1.5, as per the specification for Composite Literals. It eliminates the need to explicitly specify the type in certain situations, simplifying code.
To illustrate, consider the following anonymous struct assignment:
<code class="go">var Foo = map[string]struct{}{ "foo": struct{}{}, }</code>
Gogland may warn about the redundant type declaration. You can resolve it by using the following syntax:
<code class="go">var Foo = map[string]struct{}{ "foo": {}, }</code>
This syntax omits the type struct{} since the type is inferred from the value being assigned.
In summary, the difference between struct{}{} and {} is that the former explicitly includes the type in the composite literal, while the latter omits it, relying on the type inference of the enclosing map declaration.
The above is the detailed content of Anonymous Structs in Go: When to Use `struct{}{} vs. {}`?. For more information, please follow other related articles on the PHP Chinese website!