I saw this ..=
operator in some Rust code:
for s in 2..=9 {
// some code here
}
What is it?
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]
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.)
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.)
..=
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With