gpt4 book ai didi

go - 为什么结构内存大小与我的期望不一致?

转载 作者:行者123 更新时间:2023-12-01 21:15:33 25 4
gpt4 key购买 nike

我初始化了一个结构并计算了内存,这与我的期望不一致。

代码是:

type Man struct {
Name string
Money int
Age int32
}

func main() {

m := Man{Name:"james", Money:1000000, Age:30}

fmt.Println("man size:", unsafe.Sizeof(m))
fmt.Println("name size:", unsafe.Sizeof(m.Name))
fmt.Println("money size:", unsafe.Sizeof(m.Money))
fmt.Println("age size:", unsafe.Sizeof(m.Age))
}

结果是:
man size: 32
name size: 16
money size: 8
age size: 4


我预期的'man'大小是16 + 8 + 4 = 28,但事实是32

期待您的帮助!

最佳答案

Size and alignment guarantees:

For the numeric types, the following sizes are guaranteed:


type                                 size in bytes

byte, uint8, int8 1
uint16, int16 2
uint32, int32, float32 4
uint64, int64, float64, complex64 8
complex128 16

The following minimal alignment properties are guaranteed:
1. For a variable x of any type: unsafe.Alignof(x) is at least 1.
2. For a variable x of struct type: unsafe.Alignof(x) is the largest of all the values unsafe.Alignof(x.f) for each field f of x, but at least 1.
3. For a variable x of array type: unsafe.Alignof(x) is the same as the alignment of a variable of the array's element type.
A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory.



然后,阅读以下内容:
Memory Layouts
Padding is hard - Dave Cheney

在64位计算机上的说明:

您的类型是struct,其大小取决于基础类型的定义方式。具有相同字段但顺序不同的两个结构可能具有不同的大小。结构的大小通过填充和对齐规则进行相应计数。

Struct alignment

注意:每个彩色框为一个字节。
尝试 here,并编辑结构,然后按页面顶部的 Ask按钮。

关于go - 为什么结构内存大小与我的期望不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58810906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com