我想知道为什么第二个 fmt.Println 中的“s[1:]”没有抛出索引超出范围错误?索引 1 明显超出范围
package main
import "fmt"
func main() {
s := "J"
//fmt.Println(s[1]) // This results in a runtime error: index out of range
fmt.Println(s[1:]) // Why does this work? Index value 1 is clearly out of range, but the statement prints an empty string
}
最佳答案
作为language specification状态,给定 slice 表达式
a[low : high]
For arrays or strings, the indices are in range if
0 <= low <= high <= len(a)
, otherwise they are out of range. [...] If the indices are out of range at run time, a run-time panic occurs.
在你的例子中
s[1:]
low
是1
, high
是len(s)
和 len(s)
是1
.自 low <= len(s)
,没有 panic 。
关于去子串操作,没有索引越界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36439191/