Skip to content
Tutorials Center
My learning

Topics

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.

Rust
let ok = matches!(status, Status::Active | Status::Pending);

Try it

Rust Variants, ranges and guards

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.

Rust matches! with Option and Result

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

Rust
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-Copy data. Use ref (as in Err(ref e)) or match on a reference to avoid it.
  • No PartialEq required. 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() and opt.is_some_and(|n| n > 3) read better than matches! for Option and Result.
  • No exhaustiveness. The implicit _ => false hides new enum variants. For logic that must be revisited when a variant is added, write an explicit match.
  • In filters. matches! is a natural fit inside filter, any, all and position closures; remember that iter().filter passes &&T, so dereference or match through references as needed.
  • Related assertion: assert!(matches!(value, Pattern)) gives a poor message; prefer assert!(matches!(...), "got {value:?}").