Skip to content

Latest commit

 

History

History
78 lines (66 loc) · 2.5 KB

range-expr.md

File metadata and controls

78 lines (66 loc) · 2.5 KB

Range expressions

Syntax
RangeExpression :
      RangeExpr
   | RangeFromExpr
   | RangeToExpr
   | RangeFullExpr
   | RangeInclusiveExpr
   | RangeToInclusiveExpr

RangeExpr :
   Expression .. Expression

RangeFromExpr :
   Expression ..

RangeToExpr :
   .. Expression

RangeFullExpr :
   ..

RangeInclusiveExpr :
   Expression ..= Expression

RangeToInclusiveExpr :
   ..= Expression

The .. and ..= operators will construct an object of one of the std::ops::Range (or core::ops::Range) variants, according to the following table:

Production Syntax Type Range
RangeExpr start..end std::ops::Range start ≤ x < end
RangeFromExpr start.. std::ops::RangeFrom start ≤ x
RangeToExpr ..end std::ops::RangeTo x < end
RangeFullExpr .. std::ops::RangeFull -
RangeInclusiveExpr start..=end std::ops::RangeInclusive start ≤ x ≤ end
RangeToInclusiveExpr ..=end std::ops::RangeToInclusive x ≤ end

Examples:

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

The following expressions are equivalent.

let x = std::ops::Range {start: 0, end: 10};
let y = 0..10;

assert_eq!(x, y);

Ranges can be used in for loops:

for i in 1..11 {
    println!("{}", i);
}