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.
go tool compile -S file
a
andb
at all. Every place where references thea
andb
, it is the constant10
and5
. Even you plus/multiply something to thea
andb
, likea += 999
;b *= 999
, or print them, likefmt.Println(a, b)
. All are the constants. Nowadays, the compiler is smart enough. The variables are created in the memory only when they are used in certain cases as complicated as they have to be created. Even by then, because there is no code between the definition and the swap, thea
andb
would be set to5
and10
directly.