golang数组引用例如b [1:4]引用元素1,2,3 [英] golang array referencing eg. b[1:4] references elements 1,2,3

查看:40
本文介绍了golang数组引用例如b [1:4]引用元素1,2,3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

golang博客指出:

The golang blog states :

切片也可以通过切片"现有切片或数组来形成.切片是通过指定一个半开范围来完成的,其中两个索引之间用冒号分隔.例如,表达式b [1:4]创建包含b的元素1到3的切片(所得切片的索引将是0到2)."

"A slice can also be formed by "slicing" an existing slice or array. Slicing is done by specifying a half-open range with two indices separated by a colon. For example, the expression b[1:4] creates a slice including elements 1 through 3 of b (the indices of the resulting slice will be 0 through 2)."

有人可以向我解释上面的逻辑.IE.b [1:4]为什么不引用元素1到4?这是否与其他数组引用一致?

Can someone please explain to me the logic in the above. IE. Why doesn't b[1:4] reference elements 1 through 4? Is this consistent with other array referencing?

推荐答案

原因在切片.

对于字符串,数组或切片a,主要表达方式

For a string, array, or slice a, the primary expression

    a[low : high]

构造子字符串或切片.这索引表达式高低选择哪些元素出现在结果中.结果的索引从0开始并且长度等于高-低.

constructs a substring or slice. The index expressions low and high select which elements appear in the result. The result has indexes starting at 0 and length equal to high - low.

为方便起见,任何索引表达式可以省略.失踪低索引默认为零;失踪高索引默认为切片的操作数.

For convenience, any of the index expressions may be omitted. A missing low index defaults to zero; a missing high index defaults to the length of the sliced operand.

将切片的长度计算为高-低很容易而有效.

It's easy and efficient to calculate the length of the slice as high - low.

这篇关于golang数组引用例如b [1:4]引用元素1,2,3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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