"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > When do you need parentheses when initializing Go structs?

When do you need parentheses when initializing Go structs?

Published on 2024-11-08
Browse:584

When do you need parentheses when initializing Go structs?

Initializing Go Structs with Parentheses

When initializing structs in Go, using parentheses is not necessary but can be preferred in certain situations.

Typically, a struct is initialized using braces, as seen in:

item1 := Item{1, "Foo"}

However, it's equally valid to initialize a struct with parentheses:

item2 := (Item{2, "Bar"})

Both lines create instances of the Item struct and assign them to item1 and item2 respectively. The reflection on both structures will return the same name.

The parentheses primarily serve to disambiguate the syntax when using a struct initialization within an if statement. Without parentheses, the following code will result in a compilation error:

if i := Item{3, "a"}; i.Id == 3 {
}

The compiler cannot determine whether the opening brace belongs to the composite literal or the if statement body. Adding parentheses resolves this ambiguity:

if i := (Item{3, "a"}); i.Id == 3 {
}

In this case, the parentheses explicitly indicate that the composite literal is the value assigned to i. For further details, refer to the "Struct in for loop initializer" page.

Latest tutorial More>

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