Home >Backend Development >Golang >Why Does Go's `s[lo:hi]` Slice Exclude the Element at Index `hi`?

Why Does Go's `s[lo:hi]` Slice Exclude the Element at Index `hi`?

DDD
DDDOriginal
2024-12-09 19:36:21174browse

Why Does Go's `s[lo:hi]` Slice Exclude the Element at Index `hi`?

Why Does Go Slice s[lo:hi] End at Element hi-1?

The Go slice expression s[lo:hi] creates a slice containing elements from index lo to index hi-1, inclusive. This behavior is explained by several design principles:

Pointer Arithmetic

In Go, slices are implemented as pointers to the underlying array. Using 0-indexed arrays and inclusive-exclusive slicing allows for straightforward pointer arithmetic. The element at index i in the slice is simply the element pointed to by the slice's pointer plus i.

Length of Slice

The length of a Go slice is also the position at which to slice it. This means that arr[0:len(arr)] returns arr itself. This property is convenient for extracting data from a slice after a read or write operation.

Non-Overlapping Indices

Inclusive-exclusive slicing ensures that contiguous sub-slices of an array do not overlap. For example, if arr = [1, 2, 3, 4], then arr[0:2] = [1, 2], arr[2:4] = [3, 4], and arr[0:4] = arr. This property simplifies operations that require partitioning or manipulation of sub-slices.

Example

Consider the following Go code:

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
}

This function splits a slice of integers into consecutive sub-slices based on the difference between each element and its predecessor. The inclusive-exclusive slicing technique allows for a simpler and more efficient implementation compared to using inclusive-inclusive slicing.

The above is the detailed content of Why Does Go's `s[lo:hi]` Slice Exclude the Element at Index `hi`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn