去片长是容量-1,为什么? [英] Go slice length is capacity -1, why?

查看:131
本文介绍了去片长是容量-1,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

  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:索引表达式


a a



如果 x 在运行时超出范围,则会发生运行时恐慌

>

x 在范围内 0 <= x < ; len(a),否则它超出范围。由于 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?

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

Since there is one element after "mango" in the underlying array, capacity is 2 + 1 = 3.

Indexing the slice (tasty_fruits): spec: 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 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,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆