參考: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
}