首页 > 解决方案 > 范围代表什么?

问题描述

Rust的Ranges代表数学表达式,但仅从文档中就不清楚它们具体做了什么。

例如:

let foo = vec![0, 1, 2, 3, 4, 5];
let bar = &foo[1..=3];

具体来说,包含和排除之间有什么区别?

start < x范围和是否有特定的符号start < x < end,所以start不包括在内?

标签: rust

解决方案


这是一个表格,描述了不同的类型以及它们包含和不包含的内容。这是基于文档的示例。

类型 符号 包容性 例子
范围满 ( .. ) 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在下面定义的。手动范围也可以使用Boundhttps://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

这是因为RangeBounds定义为(Bound<T>, Bound<T>)


推荐阅读