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

huangapple go评论75阅读模式
英文:

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个元素。

这种表示法背后的思想是什么?

英文:

I can't seem to wrap my head around the notation of indices when working with Go slices.

Given a slice s.

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

I now want to create a new slice s2 = [2 3].

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

Now, what is the thought process that I should go through when accessing this value? Am I reading values starting from index 1 up to and including the third element of the slice? Or am I reading values from index 1 up to and excluding index 3?

I am not starting at index 1 and going up to index 3 and neither am I starting at position 1 and going up to position 3 as both of these would result in s2 having 3 elements.

What is the idea behind this notation?

答案1

得分: 2

从规范中提取的相关部分:切片表达式

> 对于字符串、数组、数组指针或切片 a,主表达式
>
> a[low : high]
>
> 构造一个子字符串或切片。索引 lowhigh 选择操作数 a 中出现在结果中的元素。结果的索引从 0 开始,长度等于 high - low

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

在对切片进行切片时,low 应该是你想要包含的第一个元素的索引(包含),而 high 应该是最后一个不包括的元素的索引(high不包括的)。

因此,如果你想要包含元素 [2, 3],你需要提供切片索引 13

s2 := s[1:3] // 将得到 [2, 3]

可能会让人困惑的是,切片中的元素从 1 开始,但索引从 0 开始。

关于包含-不包含索引的原因,请参考相关问题:https://stackoverflow.com/questions/26857582/in-a-go-slice-why-does-slohi-end-at-element-hi-1

英文:

Relevant section from the spec: 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.

So s2 := s[1:3] creates a new slice with length 3 - 1 = 2, so it will contain 2 elements: s[1] and s[2].

When slicing a slice, low should be the index of the first element you want to include (inclusive), and high should be the index of the last element that will not be incuded (high is exclusive).

So if you want the result to include the elements [2, 3], you need to provide slicing indices 1 and 3:

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

What might be confusing is that the elements in your slice start with 1, but the index starts with 0.

For reasoning behind the inclusive-exclusive indices, see related question: https://stackoverflow.com/questions/26857582/in-a-go-slice-why-does-slohi-end-at-element-hi-1

huangapple
  • 本文由 发表于 2016年10月29日 20:15:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/40318987.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定