go-struct memory

ref.

1
2
3
4
5
6
7
8
type myStruct struct {
myBool bool
myFloat float64 // 8 bytes
myInt int32 // 4 bytes
}

a := myStruct{}
fmt.Println(unsafe.Sizeof(a)) // 24 bytes

Because in memory we will have :
e0eadd9c.png

How to optimize :

1
2
3
4
5
6
7
8
type myStructOptimized struct {
myFloat float64 // 8 bytes
myBool bool
myInt int32 // 4 bytes
}

b := myStructOptimized{}
fmt.Println(unsafe.Sizeof(b)) // ordered 16 bytes

eed80975.png