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))
}
![](https://img.haomeiwen.com/i7304940/7beeda3a023c634c.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
网友评论