去子串操作,没有索引超出范围?

Jas*_* Gu 0 go

我想知道为什么第二个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

}
Run Code Online (Sandbox Code Playgroud)

Sav*_*ior 10

正如语言规范所述,给定切片表达式

a[low : high]
Run Code Online (Sandbox Code Playgroud)

对于数组或字符串,索引在范围内0 <= low <= high <= len(a),否则它们超出范围.[...]如果索引在运行时超出范围,则会发生运行时混乱.

在你的例子中

s[1:]
Run Code Online (Sandbox Code Playgroud)

lowIS 1,highlen(s)len(s)1.因为low <= len(s),没有恐慌.