dqfxao2898 2016-03-11 23:35
浏览 53
已采纳

Golang是这样执行多重分配的吗?

A while ago someone asked a question about how Golang actually swaps variables in statements like a, b = b, a.

To answer, I got out my Golang compiler, put on my thinking cap and crafted an answer to said question. SO questions are supposed to be self-contained, so here's my answer truncated for brevity:

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.

My comment, informed by my meager knowledge of (Intel) x86 Assembly, garnered 6 votes and my answer got an accept and 3 votes.

What are the four lines of Golang assembly actually doing? Was my answer correct?

I ask because the docs I linked to aren't very (at all) exhaustive.

  • 写回答

2条回答 默认 最新

  • doucao1888 2016-03-11 23:42
    关注
    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 
    

    CX, AX, and SP are registers. a and b are variables on the stack at SP+24 and SP+16 respectively.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序