切片:Go中出现界限错误 [英] Slicing: Out of bounds error in Go

查看:130
本文介绍了切片:Go中出现界限错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)
}

上面的代码给出了一个越界错误:

The above gives me an out of bounds error:

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 切片会导致错误?

Why is the slicing expression to create the c slice results in an error?

推荐答案

前言:问题很好,downvotes的来源是因为在冷杉乍一看,这个问题看起来像提问者根本不知道切片时的有效边界是什么。但这种情况并不常见!很少有人以一种切片的方式切片,即使下边界超出切片的长度!

Foreword: The question is good, the source of downvotes is because at first glance the question does seem like the asker simply doesn't know what the valid bounds are when slicing. But the case is uncommon! It is very rare that someone slices a slice in a way that even the lower bound is beyond the length of the slice!

简而言之:问题不在于下限可能等于或大于 len()(上限是由在切片的情况下 cap())。问题在于较高界限:它必须大于或等于下界。由于您没有指定上限,所以它默认为 len()(而不是 cap() !),它是 0 。并且 1 不小于或等于 0

In short: The problem is not with the lower bound which can be equal to or greater than len() (the upper limit is dictated by cap() in case of slices). The problem is with the higher bound: it must be greater than or equal to the lower bound. And since you didn't specify the higher bound, it defaults to len() (and not to cap()!) which is 0. And 1 is not less than or equal to 0.

规范:切片表达式

Spec: Slice expressions:


对于数组或字符串,如果 0 <= low <= high <= len(a),那么索引在范围内 code>,否则它们超出范围。对于切片,索引上限是切片容量 cap(a)而不是长度。

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.

由于您正在对切片进行切片,因此如果满足以下条件,索引将处于范围内:

Since you are slicing a slice, indices are in range if:

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

所以这一行:

c := b[1:]

无效,因为:

Is invalid, because:


缺少低指数默认为零;缺失的高指数默认为切片操作数的长度

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

So in your case low = 1 and high = 0 (implicit), which does not satisfy:

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

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

So for example the following expressions are valid:

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中出现界限错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆