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条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错