Slicing: Out of Bounds Error in Go
When executing the following code:
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) }
you encounter an "out of bounds" error. This error occurs because of an invalid slicing expression when creating the c slice.
In Go, slicing an array or slice follows these rules:
The slicing expression b[1:] attempts to create a new slice c with a lower bound of 1. However, the higher bound is missing and defaults to the length of b, which is 0. This results in a slice with a lower bound greater than its upper bound, leading to the "out of bounds" error.
To correct this error, you must ensure that the higher bound of the slicing expression is greater than or equal to the lower bound. For example, you could use the following expression to create a valid slice c:
c := b[1:2]
This creates a slice c with a lower bound of 1 and an upper bound of 2, which is valid since 1 <= 2 <= cap(b) (the capacity of b is 5).
The above is the detailed content of Why Does Slicing `b[1:]` Cause an Out-of-Bounds Error in Go?. For more information, please follow other related articles on the PHP Chinese website!