关于切片的一个问题

progyoung · 2018-10-22 22:57:00 · 1318 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2018-10-22 22:57:00 的主题,其中的信息可能已经有所发展或是发生改变。

list := []int{1}

fmt.Println(list)

fmt.Println(list[1:])

fmt.Println(list[1])

对于长度为1的切片, 取下标为1的元素会报错, 但为什么第3行能正常运行呢?


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1318 次点击  
加入收藏 微博
9 回复  |  直到 2018-10-25 08:22:23
18601400252
18601400252 · #1 · 6年之前

切片的数据结构有两个属性,len(长度)和cap(容量) 只要开始索引和结束索引不大于cap就不会出现异常,你这个例子里的len(list)==1,cap(list)==1,所以fmt.Println(list[1:])不会出异常

progyoung
progyoung · #2 · 6年之前

1楼 @18601400252 谢谢回复, 但是你是否验证过你的说法呢?

list := make([]int, 10, 20)
fmt.Println("len:", len(list))
fmt.Println("cap:", cap(list))
fmt.Println(list)
fmt.Println(list[11:])

最后一行切片的开始索引并没有超过20,但还是出错了?

254244460
254244460 · #3 · 6年之前

[a:b] ab的取值范围是0>=a>=b>=len()

a=len()似乎没什么意义,但是有时可以简化代码逻辑

iKurum
iKurum · #4 · 6年之前

[a:b] 0 <= a <= b <= cap() 当 b 省略时,a > len() 报错(panic: runtime error: slice bounds out of range) 如 list[11:] 当 b 不省略时,list[11:20] 并不会报错 go小白,并不清楚内在原因,有人解答不

sheepbao
sheepbao · #5 · 6年之前

https://golang.google.cn/ref/spec#Slice_expressions 里写了,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.

所以上面回答说不超过cap是错的,应该不超过len

a[low : high]满足 0 <= low <= high <= len(a)即可,但是对于slice,high<=cap(a)

yaohcn
yaohcn · #6 · 6年之前
iKurumiKurum #4 回复

[a:b] 0 <= a <= b <= cap() 当 b 省略时,a > len() 报错(panic: runtime error: slice bounds out of range) 如 list[11:] 当 b 不省略时,list[11:20] 并不会报错 go小白,并不清楚内在原因,有人解答不

当b省略时,编译器补全为len,即list[11:10],故报错。

wentao_toyou
wentao_toyou · #7 · 6年之前
yaohcnyaohcn #6 回复

#4楼 @iKurum 当b省略时,编译器补全为len,即list[11:10],故报错。

嗯,此为正解吧

mlzhou
mlzhou · #8 · 6年之前

fmt.Println(list[1:]) 这个不好理解? 那如果list = make([]int,0,0) list=list[0:],这样写好理解了么。类比

progyoung
progyoung · #9 · 6年之前
mlzhoumlzhou #8 回复

fmt.Println(list[1:]) 这个不好理解? 那如果list = make([]int,0,0) list=list[0:],这样写好理解了么。类比

list[1:]表示从索引为1的元素到最后一个元素, 但是list实际上并没有索引为1的元素, 所以list[1]会引发panic错误. 但是list[1:]正常, 这应该是语言层面定义的吧

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传