在使用 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 expressiona[low : high]
constructs a substring or slice. The indices
low
andhigh
select which elements of operanda
appear in the result. The result has indices starting at0
and length equal tohigh - low
.
因此 s2 := s[1:3]
创建一个长度为 3 - 1 = 2
的新 slice ,因此它将包含 2 个元素:s [1]
和 s[2]
。
slice 时,low
应该是你要包含的第一个元素的索引(inclusive),high
应该是将不包含的最后一个元素的索引(high
是不包含)。
所以如果你想让结果包含元素[2, 3]
,你需要提供 slice 索引1
和3
:
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/