简体   繁体   中英

What does initializing a Go struct in parentheses do?

Normally, I will initialize a struct like:

item1 := Item{1, "Foo"}

However, I've recently seen code initializing with parens:

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

reflect returns the same Item name.

What does initializing in parentheses do and when is it preferred?

Here's some Go code to try this out:

It does nothing special, those 2 lines are identical.

However, when you want to use that in an if statement for example, the parentheses will be required, else you get a compile time error:

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

Results in:

expected boolean expression, found simple statement (missing parentheses around composite literal?) (and 1 more errors)

This is because a parsing ambiguity arises: it's not obvious if the opening brace would be part of the composite literal or the body of the if statement.

Using parentheses will make it unambiguous for the compiler, so this works:

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

For details, see: Struct in for loop initializer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM