Simultaneous variable assignment in Go different from individual variable assignment

后端 未结 3 1501
滥情空心
滥情空心 2021-01-14 02:58

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 t

3条回答
  •  情深已故
    2021-01-14 03:27

    Assignment can be thought of as an "atomic" operation. That is, it's useful to think that all values on the left hand side of the = are "frozen" until all of the operations are finished.

    Consider the following program:

    package main
    
    import "fmt"
    
    func swap() (int, int) {
        x := 1
        y := 2
        x, y = y, x
        return x, y
    }
    
    func main() {
        fmt.Println(swap()) // prints 2 1
    }
    

    Without this "freezing" behaviour, you would get 2 for both x and y, which is probably not what you'd expect from the code. It's also probably easier to reason about the semantics of this "freezing" behaviour than if the "cascading" approach were taken.

提交回复
热议问题