Understanding Go's Slice Expression Behavior
In Go, slicing is a powerful mechanism for extracting specific elements from a slice, array, or string. However, certain behaviors may seem unexpected, such as the following:
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
Why doesn't a[3:] panic?
According to the Go language specification, for array or string slices, the indices are in range if they satisfy the following condition: 0 <= low <= high <= len(a). However, for slices, the upper index bound is cap(a) rather than len(a). In this case, the underlying array has a capacity of 3, which is equal to its length.
Therefore, a[3:] doesn't panic because the upper index bound of 3 is within the valid range determined by cap(a). It results in an empty slice, as it starts at index 3 and has a length of 0 (len(a) - 3 = 0).
Why does a[4:] panic?
On the other hand, a[4:] panics because the upper index bound of 4 exceeds both len(a) and cap(a). The specification states that indices out of range at run time will lead to a runtime panic.
The above is the detailed content of Why Doesn't Go's `a[3:]` Slice Panic, But `a[4:]` Does?. For more information, please follow other related articles on the PHP Chinese website!