I am learner of go language. This is very basic question. Please check the below sample code, and look into 3rd line.
a := [3]int{10,20}
var i int = 50
i, a[2] = 100, i
fmt.Println(i) //100
fmt.Println(a) //[10 20 50]
I have overwriten the value 100
in i
variable and immediately applied the int array. When I printed the array, the new value was not printed. How does multiple variable assignment work in go? Why the i
value is not updated into the array immediately?
The assigment section of the Go spec mentions:
The assignment proceeds in two phases.
- First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order.
- Second, the assignments are carried out in left-to-right order.
That means:
var i int = 50
i, a[2] = 100, i
a[2]
is assigned the i
evaluated before assignment (50
)i
is assigned 100
This is intended and described in the Go language specs.
Basically it is one statement which happens to assign 2 values to 2 variables. The effects of the statement are available/visible when the statement is fully executed, like with any other expression.
The value of i
changes the moment you "hit" line 4, so at the time of the assignment to a[3]
its value is still 50
.