dotj78335 2015-07-28 19:40
浏览 69
已采纳

去切片长度为容量-1,为什么?

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
  • 写回答

4条回答 默认 最新

  • dongpaipu8394 2015-07-28 19:52
    关注

    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"]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?