golang 内存对齐

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
	"fmt"
	"unsafe"
)

type A struct {
	a int32
	b int64
	c int8
	d *int8
	e struct{}
}

type B struct {
	e struct{}
	c int8
	a int32
	d *int8
	b int64
}

func main() {
	fmt.Println("the size of A is ", unsafe.Sizeof(A{}))
	fmt.Println("the size of B is ", unsafe.Sizeof(B{}))
}

输出

1
2
the size of A is  40
the size of B is  24

内存对齐前:

golang-memory-alignment.png

内存对齐后:

golang-memory-alignment-1.png