Slicing Beyond Length in Go
When slicing a slice in Go, it is possible to specify an index beyond its length. Why does this behavior occur and what are its implications?
As per the Go specification, array and slice indices are considered in range if 0 ≤ low ≤ high ≤ len(a). Thus, for arrays or strings, the indices are valid up to and including len(a). However, for slices, the upper index bound is determined by their capacity cap(a) rather than their length.
In the given example,
a := []int{1, 2, 3} fmt.Println(a[0:]) fmt.Println(a[1:]) fmt.Println(a[2:]) fmt.Println(a[3:]) // doesn't panic - why?? fmt.Println(a[4:]) // panics as expected
a[3:] does not panic because it refers to a portion of the underlying array, which extends beyond the slice's current length but remains within its capacity. This results in an empty slice. However, a[4:] triggers a panic since it exceeds the array's actual length.
According to the spec, accessing indices outside the specified range results in a runtime panic. However, in the case of slices, the capacity can be considered an extended range for slicing purposes, allowing indices up to len(a).
The above is the detailed content of Why Do Go Slices Allow Indexing Beyond Their Length Without Panicking?. For more information, please follow other related articles on the PHP Chinese website!