2

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 overwritten 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?

2
  • 2
    However this works in Go, please don't write code like this it's very confusing. Commented Jul 17, 2015 at 14:31
  • 1
    Writing the assignments on a single line doesn't make the assignments any more "immediate". Everything has to be evaluated in the specified order regardless of it being in one or more statements. Commented Jul 17, 2015 at 14:41

2 Answers 2

4

The assigment section of the Go spec mentions:

The assignment proceeds in two phases.

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
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.