参考:https://dave.cheney.net/2014/03/25/the-empty-struct#comment-2815
tips:
- 空struct的宽度为0;
- 不同的空struct,有相同的地址(https://golang.org/ref/spec#Size_and_alignment_guarantees)
type s struct {
}
type ss struct {
}
func main() {
var as, bs s
var asss, bsss ss
fmt.Printf("%p %p\n", &as, &bs) //输出 0x1181f88 0x1181f88
fmt.Printf("%p %p\n", &asss, &bsss)//输出 0x1181f88 0x1181f88
}
- struct中的对齐宽度和struct中宽度最大的成员宽度一致
type s struct {
a uint32
b uint16
}
func main() {
var test s
fmt.Println(unsafe.Alignof(test)) //输出4
fmt.Println(unsafe.Sizeof(test)) //输出8
}