In a Go slice, why does s[lo:hi] end at element hi-1?

前端 未结 2 1724
北荒
北荒 2020-12-09 19:26

According to the Tour of Go, in a Go slice s, the expression s[lo:hi] evaluates to a slice of the elements from lo through hi-1<

2条回答
  •  独厮守ぢ
    2020-12-09 19:53

    The Go Programming Language Specification

    Slice types

    Slice expressions

    For a string, array, pointer to array, or slice a, the primary expression

    a[low : high]
    

    constructs a substring or slice. The indices low and high select which elements of operand a appear in the result. The result has indices starting at 0 and length equal to high - low.

    For convenience, any of the indices may be omitted. A missing low index defaults to zero; a missing high index defaults to the length of the sliced operand

    For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length. A constant index must be non-negative and representable by a value of type int; for arrays or constant strings, constant indices must also be in range. If both indices are constant, they must satisfy low <= high. If the indices are out of range at run time, a run-time panic occurs.

    For q := p[m:n], q is a slice of p starting at index m for a length of n-m elements.

提交回复
热议问题