arrays - Go slice 长度是容量-1,为什么?

标签 arrays go slice

考虑下面的代码:

fruits := [4]string{"apple", "orange", "mango"}
tasty_fruits := fruits[1:3]
fmt.Println(len(tasty_fruits))
fmt.Println(cap(tasty_fruits))
fmt.Println(tasty_fruits)

输出:

2
3
[orange mango]

我不明白的是为什么 tasty_fruits 的容量是 3,直觉上我希望它是 2,因为那是 slice 的长度?

如果 tasty_fruits 的容量是 3,为什么:

tasty_fruits[2] = "nectarine"

结果:

panic: runtime error: index out of range

最佳答案

这一行:

fruits := [4]string{"apple", "orange", "mango"}

创建一个数组,而不是一个 slice 。它有 4 个元素,即使您只提供了 3 个元素。 fmt.Printf("%q", fruits) 的输出:

["apple" "orange" "mango" ""]

slice :

tasty_fruits := fruits[1:3]

结果:

["orange" "mango"]

长度:明明是2.容量?

The capacity is ... the sum of the length of the slice and the length of the [underlying] array beyond the slice.

因为"mango" 后面有一个元素在底层数组中,容量为 2 + 1 = 3 .

索引 slice (tasty_fruits):规范:Index expressions :

For a of slice type S: a[x]

  • if x is out of range at run time, a run-time panic occurs

x如果 0 <= x < len(a) 在范围内,否则超出范围。自 len(tasty_fruits)2 , 索引 2超出范围,因此发生运行时 panic 。

即使容量允许,您也不能对超出 slice 长度的 slice 进行索引。如果你重新 slice ,你只能到达超出长度的元素,例如:

tasty_fruits2 := tasty_fruits[:3]
tasty_fruits2[2] = "nectarine" // This is ok, len(tasty_fruits2) = 3
fmt.Printf("%q", tasty_fruits2)

输出:

["orange" "mango" "nectarine"]

关于arrays - Go slice 长度是容量-1,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31685620/

相关文章:

javascript - 获取随机范围选择的最大值

Goroutines 和依赖函数

performance - 代码顺序和性能

Python、__getitem__、切片和负索引

string - Go中如何将十六进制字符串直接转为[]byte?

Javascript将字符串切成指定长度的 block 存储在变量中

c++ - 使用模板取消分配动态二维数组

javascript - 在 Javascript 中将 Array 对象转换为 Json

go - 对结构进行分组的最惯用的方法?

python - 在python中访问列表或字符串的非连续元素