Go

What does this print? (Assignment evaluation order)

Question 8HardGo 1.22 to 1.25
i := 0
s := []int{10, 20}
i, s[i] = 1, 5
fmt.Println(i, s)

a, b := 1, 2
a, b = b, a+b
fmt.Println(a, b)

Output:

1 [5 20]
2 3

A tuple assignment happens in two phases. In phase one, the index expressions and pointer indirections on the left, and all expressions on the right, are evaluated in the usual order. In phase two, the assignments are made from left to right. So s[i] locks in index 0 before i becomes 1. This is also why a, b = b, a swaps two values without a temporary variable.

Related gotcha: in y := f() + g(), f and g are called left to right. But for operands that are not calls, the spec leaves the order open. For example, in a := 1; f := func() int { a++; return a }; x := []int{a, f()} the result can be [1 2] or [2 2], depending on the compiler. Don't write code that relies on this.

More on Language Fundamentals & Types

All 39 Language Fundamentals & Types questions