我想了解使用 make([]int, 0)
创建空 slice 时会发生什么。我执行此代码进行测试:
emptySlice := make([]int, 0)
fmt.Println(len(emptySlice))
fmt.Println(cap(emptySlice))
fmt.Println(unsafe.Sizeof(emptySlice))
size和capacity返回很明显,都是0,但是slice的size是24字节,为什么?
24 字节应该是 3 int64
对吧?一个 24 字节 slice 的内部数组应该类似于:[3]int{}
,那么为什么一个空 slice 有 24 个字节?
最佳答案
如果您阅读 documentation对于 unsafe.Sizeof
,它解释了这里发生的事情:
The size does not include any memory possibly referenced by x. For instance, if x is a slice, Sizeof returns the size of the slice descriptor, not the size of the memory referenced by the slice.
Go 中的所有数据类型都是静态大小的。即使 slice 具有动态数量的元素,也不能反射(reflect)在数据类型的大小中,因为那样它就不是静态的。
“slice 描述符”,顾名思义,就是描述一个 slice 的所有数据。这就是实际存储在 slice 变量中的内容。
Go中的 slice 有3个属性:底层数组(内存地址)、 slice 长度(内存偏移量)、 slice 容量(内存偏移量)。在 64 位应用程序中,内存地址和偏移量往往存储在 64 位(8 字节)值中。这就是为什么您看到大小为 24 (= 3 * 8 ) 字节的原因。
https://stackoverflow.com/questions/67839752/