What does initializing a Go struct in parentheses do?

旧街凉风 提交于 2019-12-05 22:38:48

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!