Go 切片索引符号背后的想法是什么?

What is the idea behind the notation of indices of Go slices?

在使用 Go 切片时,我似乎无法理解索引的表示法。

给定一个切片 s

 s := []int{1, 2, 3, 4, 5}

我现在想创建一个新切片 s2 = [2 3]

 s2 := s[1:3] // s2 = [2 3]

现在,访问这个值时我应该经过怎样的思考过程?我是否正在读取从索引 1 开始直到并包括切片的第三个元素的值?或者我是从索引 1 读取值直到并排除索引 3?

我不是从索引 1 开始到索引 3 也不是从位置 1 开始到位置 3 因为两者这些将导致 s2 有 3 个元素。

这个符号背后的想法是什么?

规范中的相关部分: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.

因此 s2 := s[1:3] 创建了一个长度为 3 - 1 = 2 的新切片,因此它将包含 2 个元素:s[1]s[2]

切片时,low应该是要包含的第一个元素的索引(包含),high应该是被包含的最后一个元素的索引(high独占)。

所以如果你想让结果包含元素[2, 3],你需要提供切片索引13:

s2 := s[1:3] // will be [2, 3]

可能令人困惑的是,切片中的元素以 1 开头,但索引以 0 开头。

有关包含-排除索引背后的推理,请参阅相关问题:In a Go slice, why does s[lo:hi] end at element hi-1?