Go中的同时变量分配不同于单个变量分配 [英] Simultaneous variable assignment in Go different from individual variable assignment

查看:70
本文介绍了Go中的同时变量分配不同于单个变量分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我给人的印象是,尽管语法有所不同,但下面的函数a和函数b在逻辑上是等效的.但是,它们不是,我也不了解它们之间的区别.

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:

  • x到变量z的值,
  • 变量y的y值,和
  • 变量y的x + y值.

有人能帮助消除我对多变量分配以及函数a和函数b之间的逻辑差异的误解吗?

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
}

推荐答案

赋值可以认为是原子"操作.也就是说,在所有操作完成之前,认为=左侧的所有值都是冻结的"很有用.

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.

请考虑以下程序:

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
}

没有这种冻结"行为,对于xy都将得到2,这可能可能不是您从代码中期望的.与采取级联"方法相比,可能更容易对这种冻结"行为的语义进行推理.

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.

这篇关于Go中的同时变量分配不同于单个变量分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆