golang数组引用例如。 b[1:4] 引用元素 1,2,3
golang 博客指出:
“切片也可以通过“切片”现有切片或数组来形成。切片是通过指定一个半开范围来完成的,其中两个索引由冒号分隔。例如,表达式 b[1:4 ] 创建一个包含 b 的元素 1 到 3 的切片(结果切片的索引将为 0 到 2)。”
有人可以向我解释一下上面的逻辑吗? IE。为什么 b[1:4] 不引用元素 1 到 4?这与其他数组引用一致吗?
The golang blog states :
"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)."
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
索引指向元素的“开始”。这是所有使用从零开始索引的语言所共有的:
支持负索引也很常见,尽管 Go 不允许这样做:
Indexes point to the "start" of the element. This is shared by all languages using zero-based indexing:
It's also common to support negative indexing, although Go doesn't allow this:
原因在 Go 语言规范的 Slices 部分给出。
计算切片长度的高 - 低非常简单且高效。
The reason is given in the Go Language Specification section on Slices.
It's easy and efficient to calculate the length of the slice as high - low.
当你认真思考时,半开区间的意义有很多。例如,对于这样的半开区间,元素的数量是:
这是一个非常漂亮且简单的公式。对于闭区间,它将是:
这(不是很多,但仍然)更复杂。
这也意味着对于例如一个字符串,整个字符串是
[1, len(s)]
这看起来也很直观。如果间隔是封闭的,要获取整个字符串,您将需要[1, len(s) + 1]
。Half-open intervals make sense for many reasons, when you get down to it. For instance, with a half-open interval like this, the number of elements is:
which is a pretty nice and easy formula. For a closed interval, it would be:
which is (not a lot, but still) more complicated.
It also means that for e.g. a string, the entire string is
[1, len(s)]
which also seems intuitive. If the interval was closed, to get the entire string you would need[1, len(s) + 1]
.与许多其他语言一样,Go 对切片使用半开间隔。用更数学的表示法来说,切片
b[1:4]
是排除上端点的区间[1,4)
。Go uses half-open intervals for slices like many other languages. In a more mathematical notation, the slice
b[1:4]
is the interval[1,4)
which excludes the upper endpoint.