Simultaneous variable assignment in Go different from individual variable assignment

Viewed 104

I was under the impression that despite the differences in syntax, function a and function b below were logically equivalent. However, they are not and I do not understand the difference between them.

It seems to me that they are both assigning:

  • the value of x to the variable z,
  • the value of y to the variable x, and
  • the value of x+y to the variable y.

Could anyone help clear up my misunderstanding regarding the multiple variable assignment and the logical difference between function a and function b?

package main

import "fmt"

func a() (int, int, int) {
    x:=1
    y:=2
    z:=3

    z = x
    x = y
    y = x+y

    return x, y, z
}

func b() (int, int, int) {
    x:=1
    y:=2
    z:=3

    z, x, y = x, y, x+y

    return x, y, z
}

func main() {
    fmt.Println(a()) // prints 2 4 1
    fmt.Println(b()) // prints 2 3 1
}
3 Answers
Related