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

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了