donglvchu9143 2016-02-29 18:49
浏览 89
已采纳

交换两个数字golang

I am trying to understand the internals of go. Consider the following code

a,b := 10,5
b,a = a,b

The above code swaps 2 number perfectly and a becomes 5 and b becomes 10. I am not able to understand how this works. Considering in the second line of code, if a is assigned to b first, then b would be 10. Now if we assign b to a then shouldn't a be 10 too.

Please help me understand how this works

Thanks

  • 写回答

1条回答 默认 最新

  • doubi12138 2016-02-29 19:29
    关注

    TL;DR: The disassembly shows that the CPU must be smart enough to see what's happening and use a register to avoid overwriting the existing value in memory.


    This question helped me learn a little more about Golang, so thank you!

    To figure out how the compiler makes native code, we need to look at the assembly code it generates, which is turned into machine code by the linker.

    I wrote a little Go program to help with this:

    package main
    
    import "fmt"
    
    func main() {
        fmt.Println(myfunction())
    }
    
    func myfunction() []int {
        a, b := 10, 5
        b, a = a, b
        return []int{a, b}
    }
    

    Using go tool compile -S > swap.s, I then <kbd>CTRL - F</kbd>'d for myfunction (which was the point of that name: easily searchable), and found these four lines, which correspond to the first two lines of myfunction in the Go code: (note this is for my 64-bit machine; the output will differ on other architechtures like 32-bit)

    0x0028 00040 (swap.go:10)   MOVQ    $10, CX         ; var a = 10
    0x002f 00047 (swap.go:10)   MOVQ    $5, AX          ; var b = 5
    0x0036 00054 (swap.go:11)   MOVQ    CX, "".b+16(SP) ; copy a to *b+16
    0x003b 00059 (swap.go:11)   MOVQ    AX, "".a+24(SP) ; copy b to *a+24 
    

    Go's disassembly is so helpful to debugging :D

    Looking at the Golang docs on asm, we can see the assembler uses indirection to juggle the values.

    When the program runs, the CPU is smart enough to see what's happening and use a register to avoid overwriting the existing value.

    Here's the full disassembly, if you're interested.

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。