string - Slice 不会在长度上出现 panic ,但在获取索引等于长度的值时会出现 panic

标签 string go indexing

我有一个 string,当我想获取 i 索引处的值时它会崩溃,但是当我切出相同的 string 保持较低的索引值作为长度然后它不会 panic 。想知道 1 和 2 有何不同?

func main() {
    str := "a"
    fmt.Println(str[1])  // 1 this panics
    fmt.Println(str[1:]) // 2 this doesn't
}

最佳答案

TLDR;在索引表达式中,索引必须小于长度,而在 slice 表达式中,长度是有效索引。

index expression 中索引必须在范围内,否则它会崩溃。如果 0 <= i < length,索引在范围内.引用规范:

In the index expression a[x]...

If a is not a map:

  • the index x is in range if 0 <= x < len(a), otherwise it is out of range

和:

For a of string type:

你的 str字符串变量存储一个 string具有单个字节的值:'a' .索引从零开始,因此单个字节的索引为 0 .它的长度是1 , 所以索引 1 处没有元素.

slice expression 中:

a[low : high]

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

在 slice 表达式中,长度是一个有效的索引。所以在你的情况下索引 str喜欢str[1:]将导致空字符串:"" :

In a slice expression a[low : high]...

The result has indices starting at 0 and length equal to high - low.

A missing low index defaults to zero; a missing high index defaults to the length of the sliced operand.

所以 str[1:]str[1:len(str)]相同这是str[1:1] .结果字符串的长度为 high - low = 1 - 1 = 0 :空string .

关于string - Slice 不会在长度上出现 panic ,但在获取索引等于长度的值时会出现 panic ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54901242/

相关文章:

go - 用于 Go 的 JMX[lang]

go - 这是在golang中的类型转换吗?

mongodb - 从MongoDB获取两个地理位置之间的距离

python - 如何有效地将 Python 列表分成 20 个 block + 一个切片作为剩余部分?

Java比较数组元素索引与索引

javascript - 从javascript中的关键字数组计算字符串中的出现次数

c++ - 如何从类型(类)转换为标准 :string?

c++ - 如何找出给定值存储在映射的哪个键下?

python - 使用python的re模块分割字符串

r - 从数据框中的第一行创建数据框的标题