给定v = vec![1,2,3,4]
,为什么v[4..]
返回一个空向量,但v[5..]
个panic ,而v[4]
和v[5]
个panic ?我怀疑这与没有指定起点或终点的切片实现有关,但我在网上找不到任何相关信息.
给定v = vec![1,2,3,4]
,为什么v[4..]
返回一个空向量,但v[5..]
个panic ,而v[4]
和v[5]
个panic ?我怀疑这与没有指定起点或终点的切片实现有关,但我在网上找不到任何相关信息.
这仅仅是因为std::ops::RangeFrom
被定义为"包含在下方的有界".
快速回顾一下所有管道:使用4..
(解析为std::ops::RangeFrom
)作为参数,从v[4..]
个desugars到std::ops::Index
个desugars.std::ops::RangeFrom
实现std::slice::SliceIndex
,Vec
对实现std::slice::SliceIndex
的任何参数都有implementation对std::ops::Index
.所以你现在看到的是一个RangeFrom
被用来代替Vec
.
std::ops::RangeFrom
定义为始终包含在下限上.例如,[0..]
将包括被索引对象的第一个元素.如果(在你的例子中)Vec
是空的,那么[0..]
将是空的片.注意:如果下限不包括在内,那么就无法在不引起panic 的情况下分割空的Vec
,这会很麻烦.
一个简单的思考方式是"篱笆柱放在哪里".
vec![0, 1, 2 ,3]
中的v[0..]
是
| 0 1 2 3 |
^
|- You are slicing from here. This includes the
entire `Vec` (even if it was empty)
v[4..]
年后就是了
| 0 1 2 3 |
^
|- You are slicing from here to the end of the Vector.
Which results in, well, nothing.
而v[5..]
就够了
| 0 1 2 3 |
^
|- Slicing from here to infinity is definitely
outside the `Vec` and, also, the
caller's fault, so panic!
v[3..]
分是
| 0 1 2 3 |
^
|- slicing from here to the end results in `&[3]`