go - Go slice 索引符号背后的想法是什么?

标签 go indexing slice

在使用 Go slice 时,我似乎无法理解索引的符号。

给定一个 slice s

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

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

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

现在,访问这个值时我应该经过怎样的思考过程?我是否正在读取从索引 1 开始直到并包括 slice 的第三个元素的值?或者我是从索引 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 的新 slice ,因此它将包含 2 个元素:s [1]s[2]

slice 时,low应该是你要包含的第一个元素的索引(inclusive),high应该是将包含的最后一个元素的索引(high不包含)。

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

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

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

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

关于go - Go slice 索引符号背后的想法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40318987/

相关文章:

go - 库网络 : Error: unknown command "/var/run/docker/netns/582bd184e561" for "some_app"

go - 数据类型突然改变

MySQL 查询优化左连接索引存在

go - 如何分组然后在 Go 中将 slice 与重复值合并

go - 如何在 fyne 中调整输入框的大小

templates - 使用golang模板打印以逗号和 "or"分隔的列表

mysql - 多个表上的索引性能

php - 使用的表类型不支持 FULLTEXT 索引

python - Numpy 切片函数 : Dynamically create slice indices np. r_[a :b, c :d, ...] 来自形状为 (X, 2) 的数组,用于在数组中进行选择

python - 按索引和列名数组对 Pandas 数据框进行切片