Home > Backend Development > Golang > Anonymous Struct in Go: When is it Redundant to Specify the Type in `map[string]struct{}`?

Anonymous Struct in Go: When is it Redundant to Specify the Type in `map[string]struct{}`?

Susan Sarandon
Release: 2024-10-30 04:06:28
Original
357 people have browsed it

 Anonymous Struct in Go:  When is it Redundant to Specify the Type in `map[string]struct{}`?

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>
Copy after login
<code class="go">var Foo = map[string]struct{}{
    "foo": {},
}</code>
Copy after login

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>
Copy after login

This is a composite literal consisting of the type (struct{}) and its value ({}). In contrast, this:

<code class="go">{}</code>
Copy after login

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 .
Copy after login

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."
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template