Assigning values to multiple variables in Go

huangapple go评论73阅读模式
英文:

Assigning values to multiple variables in Go

问题

我最近遇到了这个问题:

func main() {
    x, y := 0, 1
    x, y = y, x+y
    fmt.Println(y)
}

我原以为:

x, y = y, x+y

等同于:

x = y
y = x+y

这样的话,最终的值应该是 x = 1, y = 2

然而,我得到的最终值是 x = 1, y = 1

为什么会这样呢?

谢谢。

英文:

I recently came up across this:

func main() {
    x, y := 0, 1
    x, y = y, x+y
    fmt.Println(y)
}

What I thought was that:

x, y = y, x+y

Is identical to:

x = y
y = x+y

Which would result to final values x = 1, y = 2

However the final values I get is x = 1, y = 1

Why is that?

Thanks.

答案1

得分: 13

这是它的规定:

赋值过程分为两个阶段。首先,左边的索引表达式和指针间接引用(包括选择器中的隐式指针间接引用)的操作数以及右边的表达式按照通常的顺序进行求值。其次,按照从左到右的顺序进行赋值操作。

赋值首先对右侧的所有表达式进行求值,然后将结果赋给左侧的变量。

你的代码

x, y = y, x+y

基本上等同于以下代码

tmp1 := y
tmp2 := x+y
x = tmp1
y = tmp2

你甚至可以利用这个特性在一行中交换两个变量的值,像这样:

a, b = b, a
英文:

This is how it's specified:

> 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.

Assignment first evaluates all expressions on the right side and then assigns the results to the variables on the left side.

Your

x, y = y, x+y

is basically equivalent to this

tmp1 := y
tmp2 := x+y
x = tmp1
y = tmp2

You can even use this fact to swap 2 variables in one line, like this:

a, b = b, a

huangapple
  • 本文由 发表于 2016年12月25日 00:25:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/41314959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定