[Go] 结构体不初始化仍然能够调用其方法

背景

在写代码的时候,偶然没有将结构体初始化,又调用了该结构体的方法,编译器竟然没有报错,而且运行也是正常的。

复现

写了一个小 demo 用于复现,可以看到,声明的 Default 结构体为一个指针,而且并没有将其初始化,接着调用的该结构体的 Hello() 方法

func main() {
	var d *Default
	d.Hello()
}

type Default struct {
	HAHA string
}

func (d *Default) Hello() {
	fmt.Println("Hello")
}

期望结果是 panic,因为 d 明显是一个空指针,但是实际执行结果却是能够将 Hello 打印出来。

在这里插入图片描述

这不符合预期。

原理

在网络上搜了搜相关的文档,发现流传最广的说法如下:

在 Go 中表达式 Expression.Name 的语法,所调用的函数完全由 Expression 的类型决定。

其调用函数的指向不是由该表达式的特定运行时值来决定,包括我们前面所提到的 nil。

那么我们调用方法时原本以为是

func (d *Default) Hello()

但是实际上是

func Hello(d * Default)

这样一来,能够成功调用也就能理解了。

验证

接下来来验证一下这种说法是否正确。我们使用汇编看一下汇编出来的代码,为了减少汇编代码量,我们将 Hello() 方法里面的 fmt 打印去掉。

func (d *Default) Hello() {
	// Do nothing
}

汇编命令如下

GOOS=linux GOARCH=amd64 go tool compile -S -N -l main.go

命令解释:

  • -S 将code的汇编输出到标准输出。
  • -N 禁用优化。
  • 禁用内联。

结果如下,我们分段来进行分析

main.(*Default).Hello STEXT nosplit size=6 args=0x8 locals=0x0 funcid=0x0 align=0x0
        0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:12)  TEXT    main.(*Default).Hello(SB), NOSPLIT|NOFRAME|ABIInternal, $0-8
        0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:12)  FUNCDATA        $0, gclocals·wgcWObbY2HYnK2SU/U22lA==(SB)
        0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:12)  FUNCDATA        $1, gclocals·J5F+7Qw7O7ve2QcWC7DpeQ==(SB)
        0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:12)  FUNCDATA        $5, main.(*Default).Hello.arginfo1(SB)
        0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:12)  MOVQ    AX, main.d+8(SP)
        0x0005 00005 (/Users/xxx/work/codepractice/tmp/main.go:14)  RET
        0x0000 48 89 44 24 08 c3                                H.D$..

我们详细解释一下第一行

0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:12)  TEXT    main.(*Default).Hello(SB), NOSPLIT|NOFRAME|ABIInternal, $0-8
  • 0x0000: 当前指令相对于当前函数的偏移量。

  • main.(*Default).Hello(SB): TEXT 指令声明了 main.(*Default).Hello.text 段(程序代码在运行期会放在内存的 .text 段中)的一部分,并表明跟在这个声明后的是函数的函数体。

  • (SB): SB 是一个虚拟寄存器,保存了静态基地址(static-base) 指针,即我们程序地址空间的开始地址。 "".add(SB) 表明我们的符号位于某个固定的相对地址空间起始处的偏移位置 (最终是由链接器计算得到的)。换句话来讲,它有一个直接的绝对地址: 是一个全局的函数符号。

    所有用户定义的符号都被写为相对于伪寄存器FP(参数以及局部值)和SB(全局值)的偏移量。 SB伪寄存器可以被认为是内存的起始位置,所以对于符号foo(SB)就是名称foo在内存的地址。

    All user-defined symbols are written as offsets to the pseudo-registers FP (arguments and locals) and SB (globals). The SB pseudo-register can be thought of as the origin of memory, so the symbol foo(SB) is the name foo as an address in memory.

  • NOSPLIT: 向编译器表明不应该插入 stack-split 的用来检查栈需要扩张的前导指令。 在我们 add 函数的这种情况下,编译器自己帮我们插入了这个标记: 它足够聪明地意识到,由于 add 没有任何局部变量且没有它自己的栈帧,所以一定不会超出当前的栈;因此每次调用函数时在这里执行栈检查就是完全浪费 CPU 循环了。

    “NOSPLIT”: 不会插入前导码来检查栈是否必须被分裂。协程上的栈帧,以及他所有的调 用,都必须存放在栈顶的空闲空间。用来保护协程诸如栈分裂代码本身。

    “NOSPLIT”: Don’t insert the preamble to check if the stack must be split. The frame for the routine, plus anything it calls, must fit in the spare space at the top of the stack segment. Used to protect routines such as the stack splitting code itself.

  • NOFRAME: (对于TEXT项。)不插入指令以分配栈帧并保存/恢复返回地址,即使这不是叶子函数也是如此。仅适用于声明帧大小为0的函数。

    (For TEXT items.) Do not insert instructions to allocate a stack frame and save/restore the return address, even if this is not a leaf function. Only valid on functions that declare a frame size of 0.

  • ABIInternal:表示ABI类型为ABIInternal,不过汇编 ABIInternal 只能在 runtime 中使用。ABI0 不用写。ABIInternal 定义了一些规则,如参数传递方式、返回值处理方式等,以确保 Go 函数和汇编函数之间能够正确地进行交互。ABI0 遵循平台通用的函数调用约定,实现简单,不用担心底层cpu架构寄存器的差异;ABIInternal 可以指定特定的函数调用规范,可以针对特定性能瓶颈进行优化,在多个Go版本之间可以迭代,灵活性强,支持寄存器传参提升性能。

  • $0-8: $0 代表即将分配的栈帧大小;而 $8 指定了调用方传入的参数大小,为 8 个字节。

    通常来讲,帧大小后一般都跟随着一个参数大小,用减号分隔。(这不是一个减法操作,只是 一种特殊的语法)帧大小 $24-8 意味着这个函数有24个字节的帧以及8个字节的参数,位 于调用者的帧上。如果NOSPLIT没有在TEXT中指定,则必须提供参数大小。对于Go原型的 汇编函数,go vet会检查参数大小是否正确。

    In the general case, the frame size is followed by an argument size, separated by a minus sign. (It’s not a subtraction, just idiosyncratic syntax.) The frame size $24-8 states that the function has a 24-byte frame and is called with 8 bytes of argument, which live on the caller’s frame. If NOSPLIT is not specified for the TEXT, the argument size must be provided. For assembly functions with Go prototypes, go vet will check that the argument size is correct.

可以看到,Hello() 函数是有一个 8 个字节的入参的,而我们知道,在 64 位机器中,指针的大小正好为 8 个字节。说明我们的理论是正确的。

接下来我们可以看一下 main 对 Hello() 方法的调用。

main.main STEXT size=43 args=0x0 locals=0x18 funcid=0x0 align=0x0
        0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:3)   TEXT    main.main(SB), ABIInternal, $24-0
        0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:3)   CMPQ    SP, 16(R14)
        0x0004 00004 (/Users/xxx/work/codepractice/tmp/main.go:3)   PCDATA  $0, $-2
        0x0004 00004 (/Users/xxx/work/codepractice/tmp/main.go:3)   JLS     36
        0x0006 00006 (/Users/xxx/work/codepractice/tmp/main.go:3)   PCDATA  $0, $-1
        0x0006 00006 (/Users/xxx/work/codepractice/tmp/main.go:3)   PUSHQ   BP
        0x0007 00007 (/Users/xxx/work/codepractice/tmp/main.go:3)   MOVQ    SP, BP
        0x000a 00010 (/Users/xxx/work/codepractice/tmp/main.go:3)   SUBQ    $16, SP
        0x000e 00014 (/Users/xxx/work/codepractice/tmp/main.go:3)   FUNCDATA        $0, gclocals·g2BeySu+wFnoycgXfElmcg==(SB)
        0x000e 00014 (/Users/xxx/work/codepractice/tmp/main.go:3)   FUNCDATA        $1, gclocals·Plqv2ff52JtlYaDd2Rwxbg==(SB)
        0x000e 00014 (/Users/xxx/work/codepractice/tmp/main.go:4)   MOVQ    $0, main.d+8(SP)
        0x0017 00023 (/Users/xxx/work/codepractice/tmp/main.go:5)   XORL    AX, AX
        0x0019 00025 (/Users/xxx/work/codepractice/tmp/main.go:5)   PCDATA  $1, $0
        0x0019 00025 (/Users/xxx/work/codepractice/tmp/main.go:5)   CALL    main.(*Default).Hello(SB)
        0x001e 00030 (/Users/xxx/work/codepractice/tmp/main.go:6)   ADDQ    $16, SP
        0x0022 00034 (/Users/xxx/work/codepractice/tmp/main.go:6)   POPQ    BP
        0x0023 00035 (/Users/xxx/work/codepractice/tmp/main.go:6)   RET
        0x0024 00036 (/Users/xxx/work/codepractice/tmp/main.go:6)   NOP
        0x0024 00036 (/Users/xxx/work/codepractice/tmp/main.go:3)   PCDATA  $1, $-1
        0x0024 00036 (/Users/xxx/work/codepractice/tmp/main.go:3)   PCDATA  $0, $-2
        0x0024 00036 (/Users/xxx/work/codepractice/tmp/main.go:3)   CALL    runtime.morestack_noctxt(SB)
        0x0029 00041 (/Users/xxx/work/codepractice/tmp/main.go:3)   PCDATA  $0, $-1
        0x0029 00041 (/Users/xxx/work/codepractice/tmp/main.go:3)   JMP     0
        0x0000 49 3b 66 10 76 1e 55 48 89 e5 48 83 ec 10 48 c7  I;f.v.UH..H...H.
        0x0010 44 24 08 00 00 00 00 31 c0 e8 00 00 00 00 48 83  D$.....1......H.
        0x0020 c4 10 5d c3 e8 00 00 00 00 eb d5                 ..]........
        rel 26+4 t=7 main.(*Default).Hello+0
        rel 37+4 t=7 runtime.morestack_noctxt+0

可以看到,在第 14 行调用了该方法。

  • FUNCDATA:FUNCDATA以及PCDATA指令是 gc 相关的,暂时可以忽略。

    FUNCDATA以及PCDATA指令包含有被垃圾回收所使用的信息;这些指令是被编译器加入的。

    The FUNCDATA and PCDATA directives contain information for use by the garbage collector; they are introduced by the compiler.

验证2

既然有接收器的函数会有一个默认入参,入参是接收器本身,那么如果一个没有接收器的函数是不是就没有入参呢。

新写一个 Test() 函数

func Test() {
	// Do nothing
}

看一下汇编

main.Test STEXT nosplit size=1 args=0x0 locals=0x0 funcid=0x0 align=0x0
        0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:20)  TEXT    main.Test(SB), NOSPLIT|NOFRAME|ABIInternal, $0-0
        0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:20)  FUNCDATA        $0, gclocals·g2BeySu+wFnoycgXfElmcg==(SB)
        0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:20)  FUNCDATA        $1, gclocals·g2BeySu+wFnoycgXfElmcg==(SB)
        0x0000 00000 (/Users/xxx/work/codepractice/tmp/main.go:22)  RET
        0x0000 c3

可以看到 $0-0 代表没有入参,也从侧面印证了入参是接收器。

结论

无论方法还是函数都被存储在了 TEXT 段,拥有一个唯一的地址,使用的时候通过地址去找就可以了,而且接收器被当成了一个隐藏的入参传给函数/方法,这就导致了虽然接收器是 nil,但是如果不使用接收器的值的话,代码跑起来是完全没有问题的。

参考文档

https://www.cnblogs.com/cheyunhua/p/15755496.html

https://github.com/go-internals-cn/go-internals/blob/master/chapter1_assembly_primer/README.md

https://cloud.tencent.com/developer/article/1814882?areaId=106001

  • 18
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值