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
- Q6Explain variable shadowing. Find the bug in this code.
- Q7What are the rules for
:=redeclaration, and why does this not compile? - Q9What is the difference between a type conversion and a type assertion?
- Q10In a type switch, what is the type of the bound variable when a case lists several types, and how does
case nilbehave? - Q11How are strings represented in Go? What does this print?
- Q12What happens when you range over invalid UTF-8, and what does
string(65)produce?