go - slice : Out of bounds error in Go

标签 go slice

package main

import "fmt"

func main() {
    a := make([]int, 5)
    printSlice("a", a)
    b := make([]int, 0, 5)
    printSlice("b", b)
    c := b[1:]
    printSlice("c", c)
}


func printSlice(s string, x []int) {
    fmt.Printf("%s len=%d cap=%d %v\n",
        s, len(x), cap(x), x)
}

上面给了我一个越界错误:

a len=5 cap=5 [0 0 0 0 0]
b len=0 cap=5 []
panic: runtime error: slice bounds out of range

goroutine 1 [running]:
main.main()
   /private/var/folders/q_/53gv6r4s0y5f50v9p26qhs3h00911v/T/compile117.go:10 +0x150

为什么创建 c slice 的 slice 表达式会导致错误?

最佳答案

简而言之:问题不在于可以等于或大于len() 的下限。 (在 slice 的情况下,上限由 cap() 决定)。问题在于上限:它必须大于或等于下限。由于您没有指定上限,因此默认为 len() (而不是 cap() !)这是 0 .和 1不小于或等于 0 .

Spec: Slice expressions:

For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length.

由于您正在 slice ,索引在范围内如果:

0 <= low <= high <= cap(a)

所以这一行:

c := b[1:]

无效,因为:

A missing low index defaults to zero; a missing high index defaults to the length of the sliced operand.

所以在你的情况下low = 1high = 0 (隐式),不满足:

0 <= low <= high <= cap(a)

例如,以下表达式是有效的:

c := b[1:1]        // c len=0 cap=4 []
c := b[1:2]        // c len=1 cap=4 [0]
c := b[1:cap(b)]   // c len=4 cap=4 [0 0 0 0]

关于go - slice : Out of bounds error in Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33859066/

相关文章:

Go:嵌入原始类型?

go - 删除自己的二进制文件的可能性

go - JWT Go/Golang base64 编码负载产生不同的结果

go - 存储和检索接口(interface)的字节表示

dictionary - 如何在 Go 中获取变量的内存大小?

go - Go slice 的相等性(恒等式)

python - 如何遍历列表的前 n 个元素?

go - 整数和二进制的符号AND校验

go - 在 defer 中关闭 gzip writer 会导致数据丢失

python - 如何获取两个单词之间列表的子列表