Simultaneous variable assignment in Go different from individual variable assignment

后端 未结 3 1474
滥情空心
滥情空心 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:09

    The Go Programming Language Specification

    Assignments

    the number of operands on the left must equal the number of expressions on the right, each of which must be single-valued, and the nth expression on the right is assigned to the nth operand on the left:

    one, two, three = '一', '二', '三'
    

    The blank identifier provides a way to ignore right-hand side values in an assignment:

    _ = x       // evaluate x but ignore it
    x, _ = f()  // evaluate f() but ignore second result value
    

    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.

    Tuple assignments are two phase assignment. 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.

    For example,

    package main
    
    import "fmt"
    
    func a() (int, int, int) {
        x := 1
        y := 2
        z := 3
    
        // phase 1
        tx := x
        ty := y
    
        // phase 2
        z = tx
        x = ty
        y = tx + ty
    
        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()) 
        fmt.Println(b()) 
    }
    

    Output:

    2 3 1
    2 3 1
    

提交回复
热议问题