机构体占用一块连续的内存:
package main
import "fmt"
type test struct {
a int8
b int8
c int8
d int8
}
func main() {
type test struct {
a int8
b int8
c int8
d int8
}
n := test{
1, 2, 3, 4,
}
fmt.Printf("n.a %p\n", &n.a)
fmt.Printf("n.b %p\n", &n.b)
fmt.Printf("n.c %p\n", &n.c)
fmt.Printf("n.d %p\n", &n.d)
}
输出:
n.a 0xc0000b0004
n.b 0xc0000b0005
n.c 0xc0000b0006
n.d 0xc0000b0007
说明:
文章的演示内存对齐,采用的是int8
,因为 8 bit = 1byte
,这样输出可以更好的看到效果。
如果你用的是别的数据类型,那么会出现内存无法对齐的情况,可以采用以下链接文章中提到的方法解决。
https://segmentfault.com/a/1190000017527311