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 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题