一、求一個結構體的size

``````type S struct {
B byte  // Go中一個byte佔1字節，int32佔4個字節，int64佔8個字節
I64 int64
I32 int32
}
``````

``````type S struct {
B   byte
I64 int64
I32 int32
}

func main() {
s := S{}
fmt.Printf("s size:%d\n", unsafe.Sizeof(s))
}
``````

``````s size:24
``````

二、什麼是內存對齊

2.1 字長

``````movq (%ecx) %eax
``````

2.3 再來看結構體size的問題

``````type S struct {
B byte
I64 int64
I32 int32
}
``````

``````type S struct {
B   byte
I64 int64
I32 int32
}

func main() {
s := S{}
fmt.Printf("s size: %d, align: %d\n", unsafe.Sizeof(s), unsafe.Alignof(s))
}
``````

``````s size: 24, align: 8
``````

``````上面的結構體如果後面跟一個4字節的變量的話理論上說不用對齊也能保證一次內存IO就可加載，所以結構體對齊的根本原因目前我還不是特別能理解，可能爲編譯器做的優化，瞭解的同學歡迎在評論區指點一下
``````

``````type S struct {
B byte
I32 int32
I64 int64
}
``````

``````type S struct {
B   byte
I32 int32
I64 int64
}
func main() {
s := S{}
fmt.Printf("s size:%v, s.B地址:%v, s.I32地址:%v, s.I64地址:%v\n", unsafe.Sizeof(s), &s.B, &s.I32, &s.I64)
}
``````

``````s size:16, s.B地址:0xc0000b4010, s.I32地址:0xc0000b4014, s.I64地址:0xc0000b4018
``````