The Operators and Symbols appendix of the Rust Book lists two operators which are both right-inclusive ranges:
Operator | Example | Explanation |
---|---|---|
..= |
..=expr , expr..=expr
|
Right-inclusive range literal |
... |
expr...expr |
In a pattern: inclusive range pattern |
What is the difference between these two operators? Or, phrased differently, what is the difference between a range literal and a range pattern?
'In a pattern' suggests that expr...expr
must be used in a match expression and expr..=expr
should not be. Why is this?
A pattern is something that can be used to test if a value is a certain shape. A literal is a piece of source code that creates a value. For discoverability purposes, some literals and patterns look similar to each other, to indicate how they are related.
Rust 1.0 allowed using ...
in a pattern, so that syntax is still allowed today for backwards compatibility:
match 42 {
1...100 => println!("Just right"),
_ => println!("No good"),
}
However, Rust 1.0 did not stabilize using ...
as a literal. After much bikeshedding, we decided that ..=
was better syntax for an inclusive range. That syntax is what was stabilized in Rust 1.26 as the literal and it was also added as a pattern.
New code should prefer ..=
for patterns. The compiler even suggests updating the usage of ...
in patterns:
warning: `...` range patterns are deprecated
--> src/main.rs:3:10
|
3 | 1...100 => println!("Just right"),
| ^^^ help: use `..=` for an inclusive range
|
It is proposed that this warning will be an error in edition 2021.
The documentation could be updated to indicate that ..=
may also be used in patterns and is the preferred syntax over ...
.
See also:
This documentation's specific part is obsolete.
Inclusive range patterns were originally written ...
but were changed because this wasn't easy to decipher.
Inclusive range patterns now have the same syntax than right inclusive range literals, that is ..=
.
See Tracking issue for ..= inclusive ranges originally ...
Obviously some parts of the books and docs still need to be updated. I made a PR to change the table you noticed.
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