Slicing: Out of bounds error in Go

前端 未结 1 1456
一个人的身影
一个人的身影 2020-12-16 17:16
package main

import \"fmt\"

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


        
相关标签:
1条回答
  • 2020-12-16 17:40

    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!


    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:

    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)
    

    So this line:

    c := b[1:]
    

    Is invalid, because:

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

    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]
    
    0 讨论(0)
提交回复
热议问题