为什么我可以在Rust中从向量的末尾开始切片?
鉴于v = vec![1,2,3,4],为什么v[4..]返回一个空向量,但v[5..]恐慌,而两者v[4]和v[5]恐慌?我怀疑这与没有指定开始或端点的切片的实现有关,但我在网上找不到任何有关此的信息。
回答
这仅仅是因为std::ops::RangeFrom被定义为“包含在下面”。
快速回顾所有管道:v[4..]将std::ops::Index使用4..(解析为 a std::ops::RangeFrom)作为参数进行脱糖。std::ops::RangeFrom工具std::slice::SliceIndex和Vec具有实现的std::ops::Index任何参数实现std::slice::SliceIndex。所以,你所看到的是一个RangeFrom用来之中std::ops::Index的Vec。
std::ops::RangeFrom被定义为始终包含在下界。例如[0..]将包括被索引事物的第一个元素。如果(在您的情况下)Vec是空的,那么[0..]将是空切片。注意:如果下限不包含,则根本无法Vec在不引起恐慌的情况下切片空,这会很麻烦。
一个简单的思考方式是“栅栏柱的放置位置”。
Av[0..]中的Avec![0, 1, 2 ,3]是
| 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.
而 av[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]`