package main
import "fmt" func main() { is := []int{1, 2} fmt.Println(is[2:]) // no panic here - this includes is[2] which is out of bound still no panic fmt.Println(is[3:]) // but panic here fmt.Println(is[2]) // panic here which is acceptable }
在上面提到的程序中,即使我们正在从is [2]到on病房访问元素,并且片中只有2个元素,也没有为is [2:]感到恐慌。为什么会这样呢?
切片表达式的go规范阐明了切片所用索引的要求:
如果0 <=低<=高<=最大<= cap(a),则索引在范围内,否则它们超出范围。
对于索引表达式,相关要求是:
如果0 <= x <len(a),则索引x处于范围内,否则超出范围
你的切片有len(a) == cap(a) == 2。您的三个测试用例是:
len(a) == cap(a) == 2
low == 2
cap(a)
low == 3
x == 2
len(a)