Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Rust matches! macro

Reference for the Rust matches! macro: testing a value against a pattern, guards with if, or-patterns, ranges and how it compares to match and if let.

matches!(expr, pattern) evaluates to true if expr fits pattern and false otherwise. It is shorthand for a match with one arm returning true and a wildcard arm returning false. It is handy in filters, assertions and conditions where you only need a yes or no answer.

The pattern can use everything a match arm can: alternatives with |, ranges, tuple and struct patterns, and an if guard.

Rust
let is_vowel = matches!(c, 'a' | 'e' | 'i' | 'o' | 'u');

Try it

Rust Patterns, 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! inside iterator chains

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!(expression, pattern)
matches!(expression, pattern if guard)
matches!(expression, pat1 | pat2)
Name Description
expression The value to test. It is matched by reference-like place semantics; it is not moved unless the pattern binds by value.
pattern Any pattern, including `
guard Optional boolean condition that can use bindings from the pattern.

Returns: bool. It never panics by itself.

Usage notes

  • Bindings are local. A name bound in the pattern exists only inside the guard; matches! returns just a bool. If you need the bound value, use if let or match.
  • Moves. Matching a non-Copy value with a binding pattern by value moves it. Match on a reference (&opt) or use _ patterns when you need the value afterwards.
  • Comparison with ==. matches!(x, Foo::A) works for enums that do not implement PartialEq.
  • Readability. For two or three arms or any use of the inner value, match is clearer.
  • Exhaustiveness is not checked because the false case is a wildcard. Adding an enum variant will not produce a compile error here.
  • Works with assert!: assert!(matches!(result, Err(Error::NotFound))).