go - 将一个元素添加到 nil slice 将容量增加 2

标签 go slice

我有一个零 slice :

var s1 []int // len(s1) == 0, cap(s1) == 0

我将一个元素附加到:

s2 := append(s1, 1) // len(s2) == 1, cap(s2) == 2

为什么向 nil slice 添加一个元素会使容量增加 2?

使用 fmt.Printf 打印 slice 显示如下:

[] // s1
[1] // s2

我也很困惑为什么重新 slice s2[0:2] 显示一个既不在原始 slice 中也没有附加到它的零:

[1,0] // s2[0:2]

最佳答案

Go 可以免费为您提供超出您要求的容量。这通过减少所需的分配(可能还有复制)的数量来提高性能。容量只是在需要另一个分配之前保留的空间量。

如果您将 5 个元素附加到此 slice ,至少在我的实验中,容量为 8。这应该不足为奇,但也不应该依赖。在不同的平台,或者不同版本的编译器上,实际结果可能会有所不同,只要容量“足够大”(等于或大于长度)即可。

slice 的索引上限为 defined as its capacity :

For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length. A constant index must be non-negative and representable by a value of type int; for arrays or constant strings, constant indices must also be in range. If both indices are constant, they must satisfy low <= high. If the indices are out of range at run time, a run-time panic occurs.

这就是为什么阅读超过长度不会引起 panic 的原因。即便如此,您也不应该将这些零视为 slice 的一部分。它们可由 slice 索引,但 fmt.Printf(s2) 不会正确显示它们,因为它们不是 slice 的一部分。不要这样下标。

一般来说,您要关注的是长度,而不是容量。容量大多是可读的,以帮助优化性能。

关于go - 将一个元素添加到 nil slice 将容量增加 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38543825/

相关文章:

google-app-engine - API 错误 1 ​​(datastore_v3 : BAD_REQUEST): ApplicationError: 1 app "id1" cannot access app "id2"'s data

go - 如何将方法用作 goroutine 函数

python - 从分组列中另一个 DataFrame 的每一行创建 DataFrame?

python - 使用 2d numpy 数组切片 3d numpy 数组

Python 字符串 : obtaining what's left after python string slice

go - HUGO IN 函数不接受变量作为 ITEM

Go简单API网关代理

尽管使用了 java.NIO,但 Java Websockets 的可扩展性很差

django - 修改查询集结果

python - 计算满足条件的列部分的平均值以创建新的数据框