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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程