【发布时间】:2020-05-09 21:23:44
【问题描述】:
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:] 没有恐慌,即使我们从 is[2] 访问元素到 on 病房并且切片只有 2 个元素。为什么会这样?
【问题讨论】:
-
“为什么会这样?” 切片不是索引。
is[2:]不是“访问”is[2]。 -
@mkopriva 是的,但是不应该允许从索引 2 切片,因为它不存在。让我改写一下
is[2:]表示从is[2]到is[]结尾的元素。