Go slice的索引符号背后的想法是什么? [英] What is the idea behind the notation of indices of Go slices?

查看:64
本文介绍了Go slice的索引符号背后的想法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Go slices时,我似乎无法将索引的头围住.

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

给出一个切片 s .

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

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

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

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

现在,访问此值时应该经历什么思考过程?我是否正在读取从索引 1 一直到该切片的第三个元素的值?还是我要从索引 1 读取值,直到并排除索引 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?

我不是从索引 1 开始并上升到索引 3 ,我也不是从位置 1 开始并上升到位置 3 ,因为这两个都会导致 s2 具有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?

推荐答案

规范中的相关部分:切片表达式.

对于字符串,数组,指向数组的指针或切片 a ,主要表达式

a[low : high]

构造子字符串或切片. indices low high 选择操作数 a 的哪些元素出现在结果中.结果的索引从 0 开始,长度等于 high-low .

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] .

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].

切片时, low 应该是要包含的第一个元素的索引( inclusive ),而 high 应该是会不会插入的最后一个元素的索引( high 专有).

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).

因此,如果您希望结果包含元素 [2,3] ,则需要提供切片索引 1 3 :

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]

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

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: In a Go slice, why does s[lo:hi] end at element hi-1?

这篇关于Go slice的索引符号背后的想法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆