范围表达式
Syntax
RangeExpression →
RangeExpr
| RangeFromExpr
| RangeToExpr
| RangeFullExpr
| RangeInclusiveExpr
| RangeToInclusiveExpr
RangeExpr → Expression .. Expression
RangeFromExpr → Expression ..
RangeToExpr → .. Expression
RangeFullExpr → ..
.. 和 ..= 运算符将根据下表构造 std::ops::Range (或 core::ops::Range) 变体之一的对象:
| 产生式 | 语法格式 | 类型 | 范围 |
|---|---|---|---|
| 范围表达式 | start..end | std::ops::Range | start ≤ x < end |
| 左闭范围表达式 | start.. | std::ops::RangeFrom | start ≤ x |
| 右开范围表达式 | ..end | std::ops::RangeTo | x < end |
| 全范围表达式 | .. | std::ops::RangeFull | - |
| 闭范围表达式 | start..=end | std::ops::RangeInclusive | start ≤ x ≤ end |
| 右闭范围表达式 | ..=end | std::ops::RangeToInclusive | x ≤ end |
示例:
#![allow(unused)]
fn main() {
1..2; // std::ops::Range
3..; // std::ops::RangeFrom
..4; // std::ops::RangeTo
..; // std::ops::RangeFull
5..=6; // std::ops::RangeInclusive
..=7; // std::ops::RangeToInclusive
}
以下表达式是等价的。
#![allow(unused)]
fn main() {
let x = std::ops::Range {start: 0, end: 10};
let y = 0..10;
assert_eq!(x, y);
}
范围可以用于 for 循环:
#![allow(unused)]
fn main() {
for i in 1..11 {
println!("{}", i);
}
}