douza6300 2018-06-13 06:23 采纳率: 0%
浏览 125
已采纳

在括号中初始化Go结构会做什么?

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:

  • 写回答

1条回答 默认 最新

  • douping3891 2018-06-13 06:26
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算