douxiapi4381 2019-04-14 18:39
浏览 7
已采纳

为什么这样做有效,我在最大索引后切片了1个,却没有收到错误?

I was playing around with slices, and I found something that I can't explain. I create a string of total length 10 (index ranges from 0 to 9) and then I create a slice from it specifying one past the max index and it does not panic. It will panic if I go more than one past the last index. What am I not understanding please?

I have investigated with integer slices as well thinking there might be something odd about strings, but it showed the same behavior.

Here is an example: I expected a failure at x:= str[10:].

package main

import "fmt"

func main() {

    var str = "attribute="

    x := str[10:]
    fmt.Printf("type of x is %T
", x)
    //fmt.Printf("x is a %T and length of x is %d
", x, len(x))

    for k, v := range []byte(str) {
        fmt.Printf("%d, %x
", k, v)
    }

}

Playground: https://play.golang.org/p/Z-3YvTx3-s6

Output:

type of x is string
0, 61
1, 74
2, 74
3, 72
4, 69
5, 62
6, 75
7, 74
8, 65
9, 3d
  • 写回答

2条回答 默认 最新

  • duanbing2963 2019-04-14 18:59
    关注

    It's in the spec. Having low or high equal to the length is allowed.

    For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range.

    As to "why is this not an error": you can visualize the slicing operation as cutting between the elements. Like this:

    │   a   t   t   r   i   b   u   t   e   =    │
    │ ↑   ↑   ↑   ↑   ↑   ↑   ↑   ↑   ↑   ↑   ↑  │
    │ 0   1   2   3   4   5   6   7   8   9   10 │
    

    Technically slice point 10 is still within bounds, but it has no elements after it. That's why [10:] results in an empty string (that, or because there are no elements between low and high). This works the same way in ruby, for example. Maybe other languages too.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作