Home >Backend Development >Golang >Why Does Go's `s[lo:hi]` Slice Exclude the `hi`-th Element?
Go Slice Element Indexing: Why s[lo:hi] Ends at Element hi-1
In a Go slice, the expression s[lo:hi] evaluates to a slice of elements from position lo to position hi-1. This may seem counterintuitive, as one might expect it to include element hi. However, there are several design rationales behind this decision.
One advantage of this approach is for pointer arithmetic. In languages like C, an array is represented as a pointer to its first element. Using 0-indexed arrays and inclusive-exclusive slicing simplifies the calculation of element addresses, as the address of element i is simply the array pointer plus i.
Secondly, this indexing scheme allows for extracting the original slice by specifying arr[0:len(arr)]. This is useful in scenarios such as reading data into a slice and then extracting the non-empty slice without additional operations.
Finally, it prevents index overlap. This means that when partitioning an array into sub-slices with consecutive indices, the slices fully cover the entirety of the array. This facilitates operations such as splitting an array based on non-consecutive integers, as demonstrated in the code snippet below:
func consecutiveSlices(ints []int) [][]int { ret := make([][]int, 0) i, j := 0, 1 for j < len(ints) { if ints[j] != ints[j-1] + 1 { ret = append(ret, ints[i:j]) i = j } } ret = append(ret, ints[i:j]) return ret }
Would it have been more intuitive for s[lo:hi] to include element hi? Yes, perhaps for beginners. However, the advantages of 0-indexed arrays and inclusive-exclusive slicing, including simplified pointer arithmetic, seamless slice extraction, and non-overlapping indices, outweigh the benefits of intuitive inclusive-inclusive slicing.
The above is the detailed content of Why Does Go's `s[lo:hi]` Slice Exclude the `hi`-th Element?. For more information, please follow other related articles on the PHP Chinese website!