为什么 go 中的切片对索引 1 的长度大于长度但不能更远

shr*_*yas 6 go slice

package main

import (
    "fmt"
)

func main() {
    s:= []int{1,2}
    fmt.Println(s[0:]) // this is expected
    fmt.Println(s[1:]) // this is expected
    fmt.Println(s[2:]) // this wondering why i didn't recieve slice bounds out of range error
    fmt.Println(s[3:]) // here i recieve the error
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释为什么 s[2:] 返回空切片 [] 但 s[3:] 出错。我认为 s[2:] 也应该出错。

Ste*_*rer 5

基于Go 编程语言规范

对于数组或字符串,如果 0 <= low <= high <= len(a),则索引在范围内,否则索引超出范围。对于切片,索引上限是切片容量 cap(a) 而不是长度。

https://golang.org/ref/spec#Slice_expressions

s[3:]给出错误,因为您的low索引(即 3)大于len(s)(即 2),因此out of range

索引 low 和 high 选择操作数 a 的哪些元素出现在结果中。结果的索引从 0 开始,长度等于 high-low

s[2:]给你一个空切片,因为你的low索引(为 2)和你的high索引(默认为2golang 规范),这会导致切片长度为0( high - low)