Rust Reference ยท Patterns
Range patterns
Reference for Rust range patterns: inclusive ranges, half-open and open-ended ranges in match arms, char and integer ranges, and exhaustive matching on whole numeric types.
A range pattern matches any value that falls inside a range of integers or characters. Use it in match arms (and if let) to group many values under one branch instead of listing them with |.
The inclusive form a..=b has been available for years. Half-open a..b and open-ended a.. or ..=b patterns are also stable in current Rust, and match can be exhaustive over an entire integer type using ranges alone.
match age { 0..=12 => "child", 13..=19 => "teen", _ => "adult", }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
a..=b // inclusive: a <= x <= b a..b // exclusive end: a <= x < b a.. // from a upward ..=b // up to and including b ..b // up to but excluding b
| Part | Description |
|---|---|
| Bounds | Integer literals, char literals, constants, or paths such as u8::MAX. Must be known at compile time. |
| Type | Only integer types (including char) are accepted. Floating-point ranges in patterns are rejected in current Rust. |
| Empty ranges | An inclusive range whose start is above its end (5..=3) is a compile error (E0030). |
Errors and edge cases: a pattern like 0..=255 against a u8 covers the whole type, so a _ arm after it triggers an unreachable pattern warning. If you forget to cover a gap, the compiler lists the missing values, for example u8::MIN..=9_u8.
Usage notes
- Exhaustiveness is checked per type. For
u8andi8you can cover every value with ranges; for larger types the compiler also tracks ranges, so..0,0and1..cover all ofi32. - Overlap is allowed but wasteful. Earlier arms win, and fully shadowed arms are reported as unreachable.
- Ranges are not range values. The pattern
1..=5is not aRangeInclusive<i32>value; to test a runtime range use(1..=5).contains(&x). charranges compare scalar values, not alphabetical order, so'a'..='z'does not include accented letters. For Unicode-aware checks usechar::is_alphabeticand friends.- Bounds in guards. If the limits are not constants, use a guard:
n if n >= lo && n <= hi. - Combine with bindings using
@:n @ 1..=9names the matched number (see @ bindings).