Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a range literal and a range pattern (e.g. between `...` and `..=`)?

Tags:

rust

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?

like image 273
Javid Lakha Avatar asked May 03 '21 14:05

Javid Lakha


2 Answers

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:

  • How do I include the end value in a range?
  • What is the ..= (dot dot equals) operator in Rust?
  • Why it is not possible to use the ... syntax in expressions?
like image 162
Shepmaster Avatar answered Nov 25 '22 00:11

Shepmaster


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.

like image 45
Denys Séguret Avatar answered Nov 25 '22 00:11

Denys Séguret