我有一个 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 if0 <= x < len(a)
, otherwise it is out of range
和:
For a of string type:
- if
x
is out of range at run time, a run-time panic occurs
你的 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 tohigh - low
.A missing
low
index defaults to zero; a missinghigh
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/