机构体占用一块连续的内存:
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
本文通过Go语言展示了如何使用int8数据类型来演示内存对齐的效果,通过输出变量地址观察内存布局。文章强调了内存对齐的重要性,并提到了在不同数据类型可能导致的对齐问题,同时推荐了一篇解决内存对齐问题的文章。
1191

被折叠的 条评论
为什么被折叠?



