list := []int{1}
fmt.Println(list)
fmt.Println(list[1:])
fmt.Println(list[1])
对于长度为1的切片, 取下标为1的元素会报错, 但为什么第3行能正常运行呢?
有疑问加站长微信联系(非本文作者)

list := []int{1}
fmt.Println(list)
fmt.Println(list[1:])
fmt.Println(list[1])
对于长度为1的切片, 取下标为1的元素会报错, 但为什么第3行能正常运行呢?
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
`单行代码`
切片的数据结构有两个属性,len(长度)和cap(容量) 只要开始索引和结束索引不大于cap就不会出现异常,你这个例子里的len(list)==1,cap(list)==1,所以fmt.Println(list[1:])不会出异常
1楼 @18601400252 谢谢回复, 但是你是否验证过你的说法呢?
最后一行切片的开始索引并没有超过20,但还是出错了?
[a:b] ab的取值范围是0>=a>=b>=len()
a=len()似乎没什么意义,但是有时可以简化代码逻辑
[a:b] 0 <= a <= b <= cap() 当 b 省略时,a > len() 报错(panic: runtime error: slice bounds out of range) 如 list[11:] 当 b 不省略时,list[11:20] 并不会报错 go小白,并不清楚内在原因,有人解答不
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)
。当b省略时,编译器补全为len,即list[11:10],故报错。
嗯,此为正解吧
fmt.Println(list[1:]) 这个不好理解? 那如果list = make([]int,0,0) list=list[0:],这样写好理解了么。类比
list[1:]表示从索引为1的元素到最后一个元素, 但是list实际上并没有索引为1的元素, 所以list[1]会引发panic错误. 但是list[1:]正常, 这应该是语言层面定义的吧