为什么我可以在 Rust 中从向量的末尾开始切片?

互联网 更新时间:2023-04-26 21:00:46

use*_*968 14

这仅仅是因为std::ops::RangeFrom被定义为“包含在下面”。

快速回顾所有管道:v[4..]std::ops::Index使用4..(解析为 a std::ops::RangeFrom)作为参数进行脱糖。std::ops::RangeFrom工具std::slice::SliceIndexVec具有实现的std::ops::Index任何参数实现std::slice::SliceIndex。所以,你所看到的是一个RangeFrom用来之中std::ops::IndexVec

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]`

更多推荐

向量,末尾,切片,Rust

本文发布于:2023-04-26 21:00:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/hyzx/accfb501a638bfc0bb23a744c29963e5.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   末尾   切片   Rust

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 89740文章数
  • 23101阅读数
  • 0评论数