问题描述
请考虑以下代码:
fruits:= [4] string {apple,orange,芒果}
tasty_fruits:= fruits [1:3]
fmt.Println(len(tasty_fruits))
fmt.Println(cap(tasty_fruits))
fmt.Println tasty_fruits)
输出:
2
3
[橙芒果]
我不明白的是,为什么是tasty_fruits 3的容量,直觉上我期望它是2,因为这是片的长度?
如果tasty_fruits的容量为3,为什么:
tasty_fruits [2] =油桃
结果:
panic:运行时错误:索引超出范围
fruits:= [4] string {apple ,orange,mango}
创建数组,而不是一片。它有4个元素,即使你只提供了3.输出 fmt.Printf(%q,fruits):
[appleorangemango]
切片:
tasty_fruits:= fruits [1:3]
$ b>
结果: $ b
[orange 芒果]
长度:明显2.容量?
由于底层数组中的mango之后有一个元素,容量为 2 + 1 = 3 。
索引切片( tasty_fruits ):spec::
x 在范围内 0 ,否则它超出范围。由于 len(tasty_fruits)是 2 ,所以索引 2 超出范围,因此发生运行时恐慌。
即使容量允许,您也无法将切片索引到切片长度以外。如果您重新切片,您只能到达超出长度的元素,例如:
tasty_fruits2:= tasty_fruits [:3]
tasty_fruits2 [2] =油桃//这是好的,len(tasty_fruits2)= 3
fmt.Printf(%q,tasty_fruits2)
输出:
[orangemango 油桃]
Consider the go code below:
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)Ouputs:
2 3 [orange mango]What I don't understand is why is the capacity of tasty_fruits 3, intuitively I would expect it to be 2 since that is the length of the slice?
And if the capacity of tasty_fruits is 3 why does:
tasty_fruits[2] = "nectarine"result in:
panic: runtime error: index out of range解决方案This line:
fruits := [4]string{"apple", "orange", "mango"}Creates an array, not a slice. It has 4 elements even though you only supplied 3. Output of fmt.Printf("%q", fruits):
["apple" "orange" "mango" ""]Slicing it:
tasty_fruits := fruits[1:3]Results in:
["orange" "mango"]Length: obviously 2. Capacity?
Since there is one element after "mango" in the underlying array, capacity is 2 + 1 = 3.
Indexing the slice (tasty_fruits): spec: Index expressions:
x is in range if 0 <= x < len(a), otherwise it is out of range. Since len(tasty_fruits) is 2, the index 2 is out of range, and therefore runtime panic occurs.
You can't index the slice beyond the length of the slice, even if capacity would allow it. You can only reach the elements beyond the length if you reslice the slice, e.g.:
tasty_fruits2 := tasty_fruits[:3] tasty_fruits2[2] = "nectarine" // This is ok, len(tasty_fruits2) = 3 fmt.Printf("%q", tasty_fruits2)Output:
["orange" "mango" "nectarine"]
这篇关于去片长是容量-1,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!