GO 切片问题求教

2019 年 10 月 3 日
 jzl

初始化切片 s := make([]int, 3) 取 s[3:] 不会报越界错误,取 s[4:]就会越界了, 求教啊

4824 次点击
所在节点    Go 编程语言
13 条回复
Leigg
2019 年 10 月 3 日
这个还真没碰见过,是冷知识?
c0011
2019 年 10 月 3 日
s[3:] 是扩展切片,3 代表的是个数不是下标。
c0011
2019 年 10 月 3 日
我上边的不对。可能就是语言的规定吧,3 代表最后一个元素并且是空(nil?)
kidlj
2019 年 10 月 3 日
> For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length.

ref: https://golang.org/ref/spec#Slice_expressions

原因未知 :)
c0011
2019 年 10 月 3 日
@kidlj 但是 fmt.Println(s[3]) 会报错
kidlj
2019 年 10 月 3 日
> 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

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

因此 s[3:] == s[3:len(a)] = s[3:3] ✓
s[4:] == s[4:len(a)] == s[4:3] x
kidlj
2019 年 10 月 3 日
@c0011

> the index x is in range if 0 <= x < len(a), otherwise it is out of range

ref: https://golang.org/ref/spec#Index_expressions
kidlj
2019 年 10 月 3 日
修正:len(s) 不是 len(a)
gamexg
2019 年 10 月 3 日
故意的吧,
如果 s[3:]就报错,就无法取末尾的空切片了。
Vegetable
2019 年 10 月 3 日
错误信息是
panic: runtime error: slice bounds out of range [4:3]
6 楼说的应该就是正确答案了.
shijiu
2019 年 10 月 3 日
缺少的最高位是切片长度,而最高位是开区间,取 s[3:3]的话返回一个 0 长切片,应该是一个规定吧,方便判断。
就和 s[:0]返回一个 0 长切片一样?
dreampuf
2019 年 10 月 4 日
Carseason
2019 年 10 月 4 日
s[3:3]
s[4:3]

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/606165

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX