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
Swapper() Function in Golang is used to swaps the elements in the provided slice. To access this function, one needs to imports the reflect package in the program. Parameters: This function takes one parameters of Slice type. Return Value: This function returns the swapped slice.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With