Swap two numbers golang

前端 未结 1 1255
孤城傲影
孤城傲影 2021-02-05 09:08

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

1条回答
  •  一生所求
    2021-02-05 09:30

    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 CTRL - F'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.

    0 讨论(0)
提交回复
热议问题