【问题标题】:no panic while printing/accessing slice indexes which are out of bounds [duplicate]打印/访问超出范围的切片索引时不要惊慌[重复]
【发布时间】: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[] 结尾的元素。

标签: go slice


【解决方案1】:

go spec on slice expressions 说明了切片中使用的索引的要求:

如果 0

对于index expressions,相关要求是:

如果 0

您的切片有len(a) == cap(a) == 2。您的三个测试用例是:

  • 切片low == 2 等于cap(a)在范围内
  • 切片low == 3大于cap(a)超出范围
  • 索引x == 2等于len(a)超出范围

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2015-10-30
    相关资源
    最近更新 更多