Slice Operations in Go: Understanding the Bounds for len(slice)
Why does Go allow slicing from len(slice)? This question arises from the behavior observed in the following code snippet:
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
Explanation:
The Go specification for slice expressions states that indices are in range if 0 <= low <= high <= len(a). Importantly, for arrays and strings, the upper index bound is len(a), inclusive. For slices, the upper index bound is cap(a), which in this case is the same as len(a).
This means that the expression a[3:] does not panic because the upper index bound is allowed to be up to and including len(a). However, since the lower index bound is also 3, the resulting slice will be empty.
An index greater than len(a) will be out of range and cause a runtime panic. In the example, a[4:] panics because it tries to create a slice with an upper index bound greater than len(a).
Therefore, Go allows slicing from len(slice) because the specification explicitly allows indices up to and including len(a) for arrays and strings. This allows for convenient slicing operations without the need for explicit checks to ensure that the upper index bound is within the specified range.
The above is the detailed content of Why Doesn't Go Panic When Slicing a Slice at `len(slice)`?. For more information, please follow other related articles on the PHP Chinese website!