在Go语言中,声明和初始化的简写方式是如何评估的?

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

How the shorthand of declaration & initialization are evaluated in go lang?

问题

在Go语言中,声明和初始化的简写方式是:

var a, b, c = 1, 2, 3

这等同于以下两种声明和初始化的方式(根据规范):

a := 1
b := 2
c := 3
var a int
var b int
var c int
a = 1
b = 2
c = 3

但是,在下面的代码中,我无法得到问题的答案:

package main

import "fmt"

func main() {
    var a int = 0
    var b int = 1
    fmt.Println("init a ", a)
    fmt.Println("init b ", b)

    a, b = b, a+b
    fmt.Println("printing a after `a, b = b, a+b`", a)
    fmt.Println("printing b after `a, b = b, a+b`", b)
}

输出应该是:

printing a after 'a, b = b, a+b' 1
printing b after 'a, b = b, a+b' 2

因为b的值是通过a + b计算得出的,即1 + 1 = 2。但是它给出的结果是1。

以下是两个工作代码的Playground链接,您可以观察到它们之间的差异。

我知道我在理解上有所遗漏,特别是当同一个变量涉及到表达式时,简写表达式是如何计算的。

但是,有没有适当的文档可以参考。有人可以帮忙吗?

英文:

The shorthand for declaration and initialization in go is

var a, b, c = 1 , 2, 3 

Equivalent to following way of declaration and initialization (as per specs)

  1. a:=1
    b:=2
    c:=3

  2. var a int
    var b int
    var c int
    a=1
    b=2
    c=3

But I am not getting the answer for the problem found in following code:

package main

import "fmt"

func main() {
	var a int = 0
	var b int = 1
	fmt.Println("init a ",a)
	fmt.Println("init b ",b)	

	a, b = b, a+b
	fmt.Println("printing a after `a, b = b, a+b`",a) 
	fmt.Println("printing b after `a, b = b, a+b`",b) 

}

Output should be:

printing a after 'a, b = b, a+b' 1 
printing b after 'a, b = b, a+b' 2 

Since the value of b is evaluated with a + b i.e 1+1 = 2. But its giving 1.

Here is the playground links of both the working code where you can observe the difference.

I know I am missing something to understand, basically how the shorthand expression are evaluated especially when the same variable is involved in the expression.

But where is the proper documentation to refer. Could anyone help on this?

答案1

得分: 6

请看这里

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

根据这个规则,a+b (0+1) 首先被计算,然后被赋值。因此,你得到 a = 1 和 b = 1 的结果。

英文:

See here

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

Based on that a+b (0+1) is evaluated first. Then it's assigned. Thus you get the result of a = 1 and b = 1

huangapple
  • 本文由 发表于 2015年4月6日 19:34:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/29470466.html
匿名

发表评论

匿名网友

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

确定