32

I saw this ..= operator in some Rust code:

for s in 2..=9 {
    // some code here
}

What is it?

Lynn
  • 10,425
  • 43
  • 75

1 Answers1

44

This is the inclusive range operator.

The range x..=y contains all values >= x and <= y, i.e. “from x up to and including y”.

This is in contrast to the non-inclusive range operator x..y, which doesn't include y itself.

fn main() {
    println!("{:?}", (10..20) .collect::<Vec<_>>());
    println!("{:?}", (10..=20).collect::<Vec<_>>());
}

// Output:
//
//     [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
//     [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

Match expressions

You can also use start..=end as a pattern in a match expression to match any value in the (inclusive) range.

match fahrenheit_temperature {
    70..=89  => println!("What lovely weather!"),
    _        => println!("Ugh, I'm staying in."),
}

(Using an exclusive range start..end as a pattern is an experimental feature.)

History

Inclusive ranges used to be an experimental nightly-only feature, and were written ... before.

As of Rust 1.26, it's officially part of the language, and written ..=.

(Before inclusive ranges existed, you actually couldn't create, say, a range of byte values including 255u8. Because that'd be 0..256, and 256 is out of the u8 range! This is issue #23635.)

See also

Lynn
  • 10,425
  • 43
  • 75
  • 8
    You might want to add some detail about why this new syntax was necessary, for example the difference between `0u8..(n+1)` and `0u8..=n` when `n == 255`. – mcarton Oct 22 '18 at 15:23
  • 2
    Also, it is worth noting that `a..=b` can be used in a match expression pattern, but `a..b` in that location is experimental (`exclusive_range_pattern`)! – rodrigo Oct 22 '18 at 15:39
  • 1
    Regarding @mcarton's comment: https://stackoverflow.com/questions/32296410/ – phimuemue Oct 22 '18 at 16:06