dongyu7074 2018-02-03 12:04
浏览 16
已采纳

继续:关于多项任务的困惑

I am a bit confused about multiple assignments in Go, e.g. varA, varB = varC, varD.

My question is, is such an operation atomic (not on the HW layer of course, but from the programmer's point of view)?

Personally, I expect it to be atomic, so this expression a, b = b, a just swap the values. I tried it in the Go playground and yes, it worked exactly like that.

On the other hand, the Golang specs states:

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.

which I understand as a is assigned b's value, then b is assigned a's value (which is now b), so in the end, both a and b equals b's original value.

Are the specs wrong or do I misunderstand it?

  • 写回答

1条回答 默认 最新

  • dqotv26286 2018-02-03 12:24
    关注

    You misunderstood it, and it is not the second part you misunderstood.

    The spec say:

    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.

    Here evaluated means all expressions, including variable are ..., well, being evaluated into value and the value is fixed at that time. So in a,b = b,a, in the first part, the lhs expression a,b got resolved, and rhs expression b,a got evaluated into something like 5,3 (assuming a,b:=3,5, of course); and in the second part, the assignment took place, and becomes a = 5; b = 3.

    The evaluation is the samething happens when using defer and goroutine. It is why the below code prints 5.

    func T() {
        x := 5
        defer func(i int) {
            fmt.Println(i)
        }(x)
        x = 3
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上