Home > database >  Execution order for GoLang Struct Initializer
Execution order for GoLang Struct Initializer

Time:11-23

Was wondering if execution order for struct initialization is guaranteed in GoLang.

Does the following code always produce

obj.a == 1 and obj.b == 2 or is it unspecified behavior?

num := 0

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

type TwoNumbers struct {
    a int
    b int
}

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

CodePudding user response:

The evaluation order is specified.

The code TwoNumbers{a: nextNumber(), b: nextNumber()} is a composite literal expression. The calls to nextNumber() are operands in the 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.

The operand for field a is evaluated before the operand for field b because the operand for field a is to the left of the operand for field b.

  •  Tags:  
  • go
  • Related