为什么这样做有效,我在最大索引后切片了1个,却没有出现错误? [英] Why does this work, I am slicing 1 past max index and not getting an error?

查看:41
本文介绍了为什么这样做有效,我在最大索引后切片了1个,却没有出现错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩切片,但发现了一些我无法解释的内容.我创建了一个总长度为10的字符串(索引范围从0到9),然后从中创建一个切片,该切片指定了一个超出最大索引的值,并且它不会出现混乱.如果我超过上一个指数不止一个,那将会恐慌.请问我不明白什么?

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.

这里是一个示例:我预期在 x:= str [10:] 处失败.

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\n", x)
    //fmt.Printf("x is a %T and length of x is %d\n", x, len(x))

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

}

游乐场: https://play.golang.org/p/Z-3YvTx3-s6

输出:

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

推荐答案

它位于规范.允许 low high 等于长度.

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

对于数组或字符串,如果 0< =低< =高< = len(a),则索引在范围内,否则它们不在范围内.

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 │

从技术上讲,切片点10仍在范围内,但之后没有任何元素.这就是为什么 [10:] 生成空字符串的原因(或者是因为 low high 之间没有元素).例如,这在红宝石中的工作方式相同.也许还有其他语言.

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个,却没有出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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