简体   繁体   English

GoLang Struct Initializer 的执行顺序

[英]Execution order for GoLang Struct Initializer

Was wondering if execution order for struct initialization is guaranteed in GoLang.想知道 GoLang 是否保证了结构初始化的执行顺序。

Does the following code always produce以下代码是否总是产生

obj.a == 1 and obj.b == 2 or is it unspecified behavior? obj.a == 1obj.b == 2还是未指定的行为?

num := 0

nextNumber := func() int {
    num += 1
    return num
}

type TwoNumbers struct {
    a int
    b int
}

obj := TwoNumbers{
    a: nextNumber(),
    b: nextNumber(),
}

The evaluation order is specified.指定评估顺序。

The fields are assigned in a composite literal expression.这些字段在复合文字表达式中分配。 The specification says this about expressions in general:该规范对一般表达式进行了说明:

... when evaluating the operands of an expression, assignment, or return statement, all function calls, method calls, and communication operations are evaluated in lexical left-to-right order. ...在计算表达式、赋值或返回语句的操作数时,所有 function 调用、方法调用和通信操作都按词法从左到右的顺序进行计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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