dongyi7041 2015-04-06 11:34
浏览 36
已采纳

如何在golang中评估声明和初始化的速记?

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

  • dongtuo3530 2015-04-06 11:44
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗