TL;DR:反汇编表明CPU必须足够聪明才能看到发生了什么并使用寄存器来避免覆盖内存中的现有值。
这个问题帮助我更多地了解了Golang,所以谢谢!
为了弄清楚编译器如何生成本机代码,我们需要查看它生成的汇编代码,该汇编代码由链接器转换为机器代码。
我写了一个小 Go 程序来帮助解决这个问题:
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 的反汇编对调试非常有帮助:D
看着关于 asm 的 Golang 文档 https://golang.org/doc/asm,我们可以看到汇编器使用间接来处理这些值。
当程序运行时,CPU 足够聪明,可以看到发生了什么,并使用寄存器来避免覆盖现有值。
这是完整的拆解,如果您有兴趣的话。 http://pastebin.com/3pH8Bjt7