Introduction
In Go, when slicing an array or slice, one might expect that exceeding the length of the underlying array or slice would result in a panic. However, for slices, this behavior strangely diverges.
The Problem
Consider the following Go code:
a := []int{1, 2, 3} fmt.Println(a[0:]) fmt.Println(a[1:]) fmt.Println(a[2:]) fmt.Println(a[3:]) // Surprisingly, doesn't panic fmt.Println(a[4:]) // Panics as expected
perplexing that the slice a[3:] doesn't produce a panic, even though it appears to exceed the length of the array.
The Answer
This behavior is dictated by the Go language specification:
In our example, a is an array, and its length is 3. However, splicing up to the length of the array, i.e., a[3:], is considered within the valid range because the underlying array has a length of 3.
As the specification explains, "The upper index bound is the slice capacity cap(a) rather than the length." So, in this case, a[3:] creates an empty slice because high - low = 3 - 3 = 0.
A Key Distinction
It's important to note that using an index beyond the slice's capacity (i.e., a[4:] in our example) remains out of range and will result in a runtime panic. The specification explicitly states this: "If the indices are out of range at run time, a run-time panic occurs."
The above is the detailed content of Why Doesn't `a[len(slice)]` Panic in Go Slices?. For more information, please follow other related articles on the PHP Chinese website!