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.
let is_vowel = matches!(c, 'a' | 'e' | 'i' | 'o' | 'u');
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!(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, useif letormatch. - Moves. Matching a non-
Copyvalue 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 implementPartialEq. - Readability. For two or three arms or any use of the inner value,
matchis 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))).
Related
match,ifandelse,assert!- Lessons: Patterns, Enums and match