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.

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

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写