在打印/访问超出范围的切片索引时不会出现混乱

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:]感到恐慌。为什么会这样呢?

评论
老鸡抓小鹰
老鸡抓小鹰

The go spec on slice expressions spells out the requirements for indices used in slicing:

如果0 <=低<=高<=最大<= cap(a),则索引在范围内,否则它们超出范围。

As for index expressions, the relevant requirement is:

如果0 <= x

Your slice has len(a) == cap(a) == 2. Your three test cases are:

  • slicing: low == 2 which is equal to cap(a): in range
  • slicing: low == 3 which is greater than cap(a): out of range
  • indexing: x == 2 which is equal to len(a): out of range
点赞
评论