Rust Reference ยท Patterns
matches! patterns
Reference for using patterns with the matches! macro in Rust: testing an enum variant, a range or a guard and getting a bool without writing a full match expression.
matches!(expression, pattern) evaluates the expression and returns true if it matches the pattern, false otherwise. It is a compact way to ask "is this value of that shape?" without writing a four-line match that returns booleans.
The pattern can be anything a match arm accepts: variants, ranges, or-patterns, nested structures, and an optional if guard after the pattern. Bindings made by the pattern exist only for the guard; they are not visible afterwards.
let ok = matches!(status, Status::Active | Status::Pending);
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
matches!(EXPR, PATTERN) matches!(EXPR, PATTERN if CONDITION) matches!(EXPR, PAT1 | PAT2)
| Parameter | Description |
|---|---|
EXPR |
The value to test. It is matched by reference to the place, like in match, so a non-Copy value is not moved unless the pattern binds by value. |
PATTERN |
Any pattern. Several alternatives may be joined with |. |
if CONDITION |
Optional guard evaluated when the pattern matches. |
Returns: bool. The macro expands to a match with two arms, PATTERN => true and _ => false.
Usage notes
- No bindings escape. Names bound in the pattern can be used in the guard only. If you need the value afterwards, use
if let. - Ownership. Patterns that bind by value inside a guard may move non-
Copydata. Useref(as inErr(ref e)) or match on a reference to avoid it. - No
PartialEqrequired.matches!tests shape, so it works on types that cannot be compared with==, such as errors and enums holding closures. - Prefer simple helpers when they exist.
opt.is_some(),res.is_ok()andopt.is_some_and(|n| n > 3)read better thanmatches!forOptionandResult. - No exhaustiveness. The implicit
_ => falsehides new enum variants. For logic that must be revisited when a variant is added, write an explicitmatch. - In filters.
matches!is a natural fit insidefilter,any,allandpositionclosures; remember thatiter().filterpasses&&T, so dereference or match through references as needed. - Related assertion:
assert!(matches!(value, Pattern))gives a poor message; preferassert!(matches!(...), "got {value:?}").
Related
matches!,match, Or-patterns and match guards,Option<T>- Lessons: Patterns, match, Option basics