Go语言中的内存布局详解

2020-01-28 12:27:29于海丽


type MyData struct {
       aByte       byte
       anotherByte byte
       aShort      int16
       anInt32     int32
       aSlice      []byte
}

我们再次运行反射代码,可以看到anotherByte正好在aByte和aShort之间的空闲空间。 它坐落在偏移1,aShort仍然在偏移2.现在可能是时候注意我之前提到的那个神秘对齐字段。 它告诉我们和Go编译器,这个字段需要如何对齐。


Struct is 32 bytes long
aByte at offset 0, size=1, align=1
anotherByte at offset 1, size=1, align=1
aShort at offset 2, size=2, align=2
anInt32 at offset 4, size=4, align=4
aSlice at offset 8, size=24, align=8

三、看看内存

然而我们的结构体在内存中到底是什么样子? 让我们看看我们能不能找到答案。 首先让我们构建一个MyData实例,并填充一些值。我选择了应该容易在内存中找到的值。


data := MyData{
        aByte:   0x1,
        aShort:  0x0203,
        anInt32: 0x04050607,
        aSlice:  []byte{
                0x08, 0x09, 0x0a,
        },
 }

现在一些代码访问组成这个结构的字节。 我们想要获取这个结构的实例,在内存中找到它的地址,并打印出该内存中的字节。

我们使用unsafe包来帮助我们这样做。 这让我们绕过Go类型系统将指向我们的结构的指针转换为32字节数组,这个数组就是组成我们的结构体的内存数据。


dataBytes := (*[32]byte)(unsafe.Pointer(&data))
fmt.Printf("Bytes are %#vn", dataBytes)

我们运行以上代码。 这是结果,第一个字段,aByte,从我们的结构中以粗体显示。 这是希望你期望的,单字节aByte = 0x01在偏移0。


Bytes are &[32]uint8{**0x1**, 0x0, 0x3, 0x2, 0x7, 0x6, 0x5, 0x4, 0x5a, 0x5, 0x1, 0x20, 0xc4, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}

接下来我们来看看AShort。 这是在偏移量2的位置并且长度为2.如果你记得,aShort = 0x0203,但数据显示的字节是倒序。 这是因为大多数现代CPU都是Little-Endian:该值的最低位字节首先出现在内存中。


Bytes are &[32]uint8{0x1, 0x0, **0x3, 0x2**, 0x7, 0x6, 0x5, 0x4, 0x5a, 0x5, 0x1, 0x20, 0xc4, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}