doc.rust-lang.org
match expressions
MatchExpression ->
`match` Scrutinee `{`
InnerAttribute*
MatchArms?
`}`
Scrutinee -> Expression _except [StructExpression]_
MatchArms ->
( MatchArm `=>` ( ExpressionWithoutBlock `,` | ExpressionWithBlock `,`? ) )*
MatchArm `=>` Expression `,`?
MatchArm -> OuterAttribute* Pattern MatchArmGuard?
MatchArmGuard -> `if` MatchConditions
MatchConditions ->
MatchGuardChain
| Expression
MatchGuardChain -> MatchGuardCondition ( `&&` MatchGuardCondition )*
MatchGuardCondition ->
Expression _except [ExcludedMatchConditions]_
| OuterAttribute* `let` Pattern `=` MatchGuardScrutinee
MatchGuardScrutinee -> Expression _except [ExcludedMatchConditions]_
@root ExcludedMatchConditions ->
LazyBooleanExpression
| RangeExpr
| RangeFromExpr
| RangeInclusiveExpr
| AssignmentExpression
| CompoundAssignmentExpression...
The Rust Reference
Book
2024-01-01
~6 min read
doc.rust-lang.org
Argument parsing
Matching can be used to parse simple arguments:
use std::env;
fn increase(number: i32) {
println!("{}", number + 1);
}
fn decrease(number: i32) {
println!("{}", number - 1);
}
fn help() {
println!("usage:
match_args <string>
Check whether given string is the answer.
match_args {{increase|decrease}} <integer>
Increase or decrease given...
Rust by Example
Book
2024-01-01
~1 min read
rustc-dev-guide.rust-lang.org
Pattern and exhaustiveness checking
In Rust, pattern matching and bindings have a few very helpful properties. The compiler will check that bindings are irrefutable when made and that match arms are exhaustive.
Pattern usefulness
The central question that usefulness checking answers is: "in this match expression, is that branch redundant...
Guide to Rustc Development
Book
2024-01-01
~6 min read
blog.knoldus.com
...matches macro!
matches(macro) is provided by Rust’s standard library and an external crate called matches.Here we’ll talk about the matches macro provided by our standard library only, although both matches provide the same functionality but let’s focus on the official one.
So matches checks whether...
Rust Walkthroughs
2020-12-30
~2 min read
blog.cuongle.dev
Rust’s pattern matching feels simple enough: match on enums, destructure tuples, handle Option and Result. I stuck with these basics for months because, well, they work. But there’s a whole world of pattern techniques I wasn’t using. Once I discovered what’s actually possible, I kicked myself...
Rust Walkthroughs
2025-10-01
~4 min read
doc.rust-lang.org
...We’ll talk about match guards later in the “Adding Conditionals with Match Guards” section.
Matching Multiple Patterns
In match expressions, you can match multiple patterns using the | syntax, which is the pattern or operator. For example, in the following code, we match the value of x against the match...
The Rust Programming Language
Book
2024-02-01
~19 min read
doc.rust-lang.org
match
Rust provides pattern matching via the match keyword, which can be used like a C switch. The first matching arm is evaluated and all possible values must be covered.
fn main() {
let number = 13;
// TODO ^ Try different values for `number`
println!("Tell me about {}", number);
match number {
// Match a...
Rust by Example
Book
2024-01-01
~1 min read
github.com
...Needs filling in.
### Multiple branches
All of these matches are equivalent, each written in a different style:
```rust
use E::*;
enum E { A, B, C, D }
match foo {
A | B => println!("Give me A | B!"),
C | D => println!("Give me C | D!"),
}
match foo {
| A | B => println!("Give me A...
RFC 1925
RFC
2017-02-23
~4 min read
github.com
## Summary
[summary]: #summary
Better ergonomics for pattern-matching on references.
Currently, matching on references requires a bit of a dance using
`ref` and `&` patterns:
```rust
let x: &Option<_> = &Some(0);
match x {
&Some(ref y) => { ... },
&None => { ... },
}
// or using `*`:
match *x {
Some(ref x) => { ... },
None => { ... },
}
```
After this RFC, the above form...
RFC 2005
RFC
2016-08-12
~12 min read
github.com
## Summary
[summary]: #summary
Allow `if let` guards in `match` expressions.
## Motivation
[motivation]: #motivation
This feature would greatly simplify some logic where we must match a pattern iff some value computed from the `match`-bound values has a certain form, where said value may be costly or impossible (due to affine...
RFC 2294
RFC
2018-01-15
~5 min read
doc.rust-lang.org
The match Control Flow Construct
Rust has an extremely powerful control flow construct called match that allows you to compare a value against a series of patterns and then execute code based on which pattern matches. Patterns can be made up of literal values, variable names, wildcards, and many other...
The Rust Programming Language
Book
2024-02-01
~9 min read
smallcultfollowing.com
...Void) {
match v { }
}
In effect, this match serves as a kind of assertion. You are saying
“because v can never be instantiated, foo could never actually be
called, and therefore – when I match against it – this match must
be dead code”. Since the match is dead code, you don’t...
News & Blog Posts
2018-08-14
~14 min read
github.com
## Summary
Change array/slice patterns in the following ways:
- Make them only match on arrays (`[T; n]` and `[T]`), not slices;
- Make subslice matching yield a value of type `[T; n]` or `[T]`, not `&[T]` or
`&mut [T]`;
- Allow multiple mutable references to be made to different parts of the...
RFC 495
RFC
2014-12-03
~3 min read
doc.rust-lang.org
...For example, these two matches on x: &i32 are equivalent:
let int_reference = &3;
let a = match *int_reference { 0 => "zero", _ => "some" };
let b = match int_reference { &0 => "zero", _ => "some" };
assert_eq!(a, b);
The grammar production for reference patterns has to match the token && to match a reference to...
The Rust Reference
Book
2024-01-01
~26 min read
www.ncameron.org
...For example, if we have a pattern ab?c and a single match which has matched a in the input then we can fork and one match will attempt to match b then c, and one will just match c.
One interesting aspect of matching is handling metavariable matching in...
News & Blog Posts
2019-01-22
~4 min read
doc.rust-lang.org
if let
For some use cases, when matching enums, match is awkward. For example:
// Make `optional` of type `Option<i32>`
let optional = Some(7);
match optional {
Some(i) => println!("This is a really long string and `{:?}`", i),
_ => {},
// ^ Required because `match` is exhaustive. Doesn't it seem
// like wasted space?
};
if...
Rust by Example
Book
2024-01-01
~2 min read
xion.io
Rust is one of those nice languages with pattern matching.
If you don’t know, it can be thought of as a generalization of the switch statement:
comparing objects not just by value (or overloaded equality operator, etc.)
but by structure:
match hashmap.get(&key) {
Some(value) => do_something_with...
News & Blog Posts
2016-06-06
~5 min read
doc.rust-lang.org
...match Arms
As discussed in Chapter 6, we use patterns in the arms of match expressions. Formally, match expressions are defined as the keyword match, a value to match on, and one or more match arms that consist of a pattern and an expression to run if the value matches...
The Rust Programming Language
Book
2024-02-01
~7 min read
rustexp.lpil.uk
...K keep text out of match
\G anchor to previous match
\Z anchor to the end of the text before any trailing newlines
\O any character including newline
Capture groups and backreferences
\1 match first capture group
\2 match second capture group
\{N} match Nth capture group
(?<name> exp)
capture...
Crate of the Week
2019-07-09
~1 min read
rust.code-maven.com
...Using match on Option
fn match_on_option(animal: &str) {
let text = "The black cat climbed the green tree";
match text.find(animal) {
Some(location) => println!("Location of {animal}: {location}"),
None => println!("None received - no {animal} found"),
};
}
Calling match_on_option("cat"); will print Location of cat: 10. Calling match...
Miscellaneous
2024-01-10
~3 min read