Slicing: error outside error in 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 error beyond:

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

Why does the slicing expression to create a segment cresult in an error?

+4
source share
1 answer

Preface: The question is good, the source of downvotes is because at first glance the question seems to be that the asker simply does not know what the actual boundaries are when slicing. But the case is unusual! Very rarely, someone cuts a slice so that even the lower boundary goes beyond the slice!


: , len() ( cap() ). : . , len() ( cap()!)), 0. 1 0.

Spec: :

, 0 <= low <= high <= len(a), . - cap(a), .

, , :

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

, :

c := b[1:]

, :

; .

, low = 1 high = 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]
+8

Source: https://habr.com/ru/post/1616966/


All Articles