gpt4 book ai didi

assembly - 这是 Golang 执行多重赋值的方式吗?

转载 作者:IT王子 更新时间:2023-10-29 00:55:46 25 4
gpt4 key购买 nike

前段时间有人问a question关于 Golang 实际上如何在 a, b = b, a 等语句中交换变量。

为了回答这个问题,我拿出了我的 Golang 编译器,戴上了我的思维帽并制作了 an answer说的问题。所以问题应该是独立的,所以为了简洁起见,我的答案被截断了:

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 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

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.

我的 comment ,根据我对(英特尔)x86 汇编的微薄知识,获得了 6 票,我的回答获得了接受和 3 票。

Golang 汇编的四行代码实际上在做什么我的回答正确吗?

我问是因为 docs我链接到的不是很(完全)详尽无遗。

最佳答案

a, b := 10, 5
b, a = a, b

0x0028 00040 (swap.go:10) MOVQ $10, CX ; CX = 10
0x002f 00047 (swap.go:10) MOVQ $5, AX ; AX = 5
0x0036 00054 (swap.go:11) MOVQ CX, "".b+16(SP) ; b = CX or *(SP+16) = CX
0x003b 00059 (swap.go:11) MOVQ AX, "".a+24(SP) ; a = AX or *(SP+24) = CX

CXAXSP 是寄存器。 ab分别是SP+24和SP+16栈上的变量。

关于assembly - 这是 Golang 执行多重赋值的方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35951805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com