gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:38:52 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com