在括号中初始化Go结构有什么作用? [英] What does initializing a Go struct in parentheses do?

查看:109
本文介绍了在括号中初始化Go结构有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我将初始化一个结构:

Normally, I will initialize a struct like:

item1 := Item{1, "Foo"}

但是,我最近看到了用parens初始化的代码:

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

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

reflect 返回相同的 Item 名称.

括号中的内容有什么用,什么时候首选?

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

这里有一些Go代码可以尝试:

Here's some Go code to try this out:

推荐答案

它没什么特别的,这两行是相同的.

It does nothing special, those 2 lines are identical.

但是,例如,当您想在 if 语句中使用它时,将需要使用括号,否则会出现编译时错误:

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 {
}

结果:

期望的布尔表达式,找到了简单的语句(是否在合成文字周围缺少括号?)(以及另外1个错误)

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

这是因为产生了解析歧义:左括号是否是复合文字或 if 语句主体的一部分,这并不明显.

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循环初始化器

For details, see: Struct in for loop initializer

这篇关于在括号中初始化Go结构有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆