rust - 范围代表什么?
问题描述
Rust的Ranges代表数学表达式,但仅从文档中就不清楚它们具体做了什么。
例如:
let foo = vec![0, 1, 2, 3, 4, 5];
let bar = &foo[1..=3];
具体来说,包含和排除之间有什么区别?
start < x
范围和是否有特定的符号start < x < end
,所以start
不包括在内?
解决方案
这是一个表格,描述了不同的类型以及它们包含和不包含的内容。这是基于文档的示例。
类型 | 符号 | 包容性 | 例子 |
---|---|---|---|
范围满 | ( .. ) |
x |
arr[ .. ]==[0, 1, 2, 3, 4] |
范围 | (1.. ) |
start <= x |
arr[1.. ]==[ 1, 2, 3, 4] |
范围 | (1.. 3) |
start <= x < end |
arr[1.. 3]==[ 1, 2 ] |
范围包括 | (1..=3) |
start <= x <= end |
arr[1..=3]==[ 1, 2, 3 ] |
范围至 | ( .. 3) |
x < end |
arr[ .. 3]==[0, 1, 2 ] |
RangeToInclusive | ( ..=3) |
x <= end |
arr[ ..=3]==[0, 1, 2, 3 ] |
无固定类型 | 见下文 | start < x |
____1____ ==[ 2, 3, 4] |
无固定类型 | 见下文 | start < x < end |
____1___3 ==[ 2 ] |
无固定类型 | 见下文 | start < x <= end |
____1__=3 ==[ 2, 3 ] |
正如Stargateur在下面定义的。手动范围也可以使用Bound
(https://doc.rust-lang.org/std/ops/enum.Bound.html)定义。最后3种情况可以定义如下:
use std::ops::Bound::{Excluded, Included, Unbounded};
use std::ops::RangeBounds;
(Excluded(1), Unbounded).contains(&2) // start < x
(Excluded(1), Excluded(3)).contains(&2) // start < x < end
(Excluded(1), Included(3)).contains(&2) // start < x <= end
推荐阅读
- mysql - 如何在sql中对带有文本的数字进行数字排序?
- c - 如何修复“tcc: library not found”错误?
- c# - 填写 Excel 时出现 OutOfMemoryException
- .net - 如何在 EF Core 中创建分区表?
- node.js - 在一个应用程序中提取所有社交应用程序的数据
- excel - 带有 vbNarrow 的 VBA StrConv 抛出运行时错误“5”
- tensorflow - how to train image segmentation task on tpu's in colab?
- javascript - 使用 DOMPurify 清理 HTML 时允许属性的安全含义
- docker - is a running container created by each RUN command during multistage build?
- java - 为什么hazelcast不能用imap和hazelcastjsonvalue查询不正确的结果