go - 为什么一个空 slice 有 24 个字节?

我想了解使用 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/

相关文章:

php - laravel sanctum 路线 [登录名] 未定义

typescript - noFallthroughCasesInSwitch - 明确允许失败

javascript - 接收错误 : xhr poll error socket. io 客户端

go - 为什么 math.Pow 的性能比位移差?

python - 如何比较列表与列表的不均匀列表

c++ - 当我们已经拥有更强大的 vector 时,为什么还需要堆栈?

c# - 为什么将 List 转换为 Array 而不是在 C# 中引用?

windows - 将 Systems Internals 列为制造商的 Windows 服务的名称

c - getc 不止一次评估流

python - 在 [任何以前的版本] 之前的 Python 中这可能吗