多变量赋值是如何工作的?

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

How does multiple variable assignment work?

问题

请检查下面的示例代码,并查看第三行。

a := [3]int{10,20} 
var i int = 50
i, a[2] = 100, i

fmt.Println(i)   //100
fmt.Println(a)   //[10 20 50]

我已经覆盖了变量i中的值100,并立即应用到整型数组中。当我打印数组时,新值没有被打印出来。在Go语言中,多变量赋值是如何工作的?为什么i的值没有立即更新到数组中?

英文:

Please check the below sample code, and look into 3rd line.

a := [3]int{10,20} 
var i int = 50
i, a[2] = 100, i

fmt.Println(i)   //100
fmt.Println(a)   //[10 20 50]

I have overwritten the value 100 in i variable and immediately applied the int array. When I printed the array, the new value was not printed. How does multiple variable assignment work in Go? Why the i value is not updated into the array immediately?

答案1

得分: 4

Go语言规范中的赋值部分提到:

> 赋值过程分为两个阶段。

> - 首先,左边的索引表达式和指针间接引用(包括选择器中的隐式指针间接引用)以及右边的表达式都按照通常的顺序进行求值

  • 其次,按照从左到右的顺序进行赋值。

这意味着:

var i int = 50
i, a[2] = 100, i
  • a[2] 被赋值为在赋值之前求值的 i(即 50

  • i 被赋值为 100

英文:

The assigment section of the Go spec mentions:

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

That means:

var i int = 50
i, a[2] = 100, i
  • a[2] is assigned the i evaluated before assignment (50)

  • i is assigned 100

答案2

得分: 3

这是在Go语言规范中描述和解释的。

基本上,这是一个语句,它同时将两个值分配给两个变量。语句的效果在语句完全执行时可见,就像其他任何表达式一样。

变量i的值在第4行被执行时发生改变,所以在将值赋给a[3]时,它的值仍然是50

英文:

This is intended and described in the Go language specs.

Basically it is one statement which happens to assign 2 values to 2 variables. The effects of the statement are available/visible when the statement is fully executed, like with any other expression.

The value of i changes the moment you "hit" line 4, so at the time of the assignment to a[3] its value is still 50.

huangapple
  • 本文由 发表于 2015年7月17日 22:22:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/31478069.html
匿名

发表评论

匿名网友

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

确定