go 的空结构体为什么 size == 0?

2022-08-28  本文已影响0人  wayyyy
type EmptyStruct struct{}

func main() {
    a := struct{}{}
    b := struct{}{}
    c := EmptyStruct{}

    fmt.Printf("%p\n", &a)
    fmt.Printf("%p\n", &b)
    fmt.Printf("%p\n", &c)

    fmt.Println(unsafe.Sizeof(a))
}
image.png

从上面可以看出,空结构体的变量的内存地址都是一样的,这是因为:
编译器在编译期间,识别到 size == 0 这种特殊类型的内存分配,会统统分配出 runtime.zerobase 的地址出去,这个代码逻辑是在 mallocgc 函数里面:

func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
    if gcphase == _GCmarktermination {
        throw("mallocgc called with gcphase == _GCmarktermination")
    }

    if size == 0 {
        return unsafe.Pointer(&zerobase)
    }
    ...
}
空结构体对齐规则

TODO

上一篇 下一篇

猜你喜欢

热点阅读