golang中的内存对齐演示

Posted 李斌的BLOG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang中的内存对齐演示相关的知识,希望对你有一定的参考价值。

机构体占用一块连续的内存:

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

以上是关于golang中的内存对齐演示的主要内容,如果未能解决你的问题,请参考以下文章

Golang优化之内存对齐

Golang内存对齐

golang 转到片段以观察运行时行为和内存分配

golang goroutine例子[golang并发代码片段]

golang代码片段(摘抄)

按位或运算符 | C中用于对齐内存块的用法[重复]