考虑下面的代码:
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 typeS
: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/