package mainimport "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 個元素。為什么會這樣?
1 回答

湖上湖
TA貢獻2003條經(jīng)驗 獲得超2個贊
切片表達式的go 規(guī)范闡明了切片中使用的索引的要求:
如果 0 <= low <= high <= max <= cap(a),則索引在范圍內(nèi),否則超出范圍。
至于索引表達式,相關(guān)要求是:
如果 0 <= x < len(a),則索引 x 在范圍內(nèi),否則超出范圍
你的切片有len(a) == cap(a) == 2
. 您的三個測試用例是:
切片:
low == 2
等于cap(a)
:在范圍內(nèi)切片:
low == 3
大于cap(a)
:超出范圍索引:
x == 2
等于len(a)
:超出范圍
- 1 回答
- 0 關(guān)注
- 164 瀏覽
添加回答
舉報
0/150
提交
取消