douqiang6036 2016-03-11 22:59
浏览 39
已采纳

Go中的同时变量分配不同于单个变量分配

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条回答 默认 最新

  • dongqu5650 2016-03-11 23:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解