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 wards,而且分片只有2个元素,is[2:]也不会出现恐慌。为什么会这样呢?
该 去规范切片的表达方式 规定了对切片中使用的指数的要求。
如果0<=低<=高<=最大<=上限(a),指数就在范围内,否则就超出范围。
至于 索引表达式,相关要求是
指数x在0 <= x < len(a)范围内,否则超出范围。
你的片子已经 len(a) == cap(a) == 2
. 你的三个测试用例是
low == 2
这等于 cap(a)
: 在范围内low == 3
大于 cap(a)
: 不在范围内x == 2
这等于 len(a)
: 不在范围内