Pattern Matching
Destructure and branch with match, if let, and advanced patterns. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Search across all documentation pages
Destructure and branch with match, if let, and advanced patterns. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Exhaustive arms with | alternatives and _ catch-all.
match 2 {
1 | 2 => "small",
_ => "big",
} // "small"Handle one pattern without a full match.
let v = Some(3);
if let Some(n) = v { n } else { 0 } // 3Loop while a pattern matches.
let mut stack = vec![1, 2];
let mut sum = 0;
while let Some(n) = stack.pop() { sum += n; }
sum // 3Add if conditions after a pattern.
let n = 4;
match n {
x if x % 2 == 0 => "even",
_ => "odd",
} // "even"Bind a name while testing a pattern.
match 5 {
n @ 1..=10 => n,
_ => 0,
} // 5Pull fields out in match or let.
struct P { x: i32, y: i32 }
let P { x, y } = P { x: 1, y: 2 };
x + y // 3Nested tuple patterns.
let ((a, b), c) = ((1, 2), 3);
a + b + c // 6Discard values you do not need.
let (x, _) = (1, 99);
x // 1Match through Option and custom enums.
enum E { A(i32), B }
match Some(E::A(7)) {
Some(E::A(n)) => n,
_ => 0,
} // 7Match prefixes of slices (stable patterns).
match &[1, 2, 3][..] {
[a, b, ..] => a + b,
_ => 0,
} // 3Combine patterns deeply.
match (true, 1) {
(true, 1 | 2) => "ok",
_ => "no",
} // "ok"Boolean test without binding.
matches!(Some(1), Some(_)) // trueDiverge on failed pattern (let-else).
let Some(n) = Some(3) else { panic!("none") };
n // 3Borrow mutably inside a match.
let mut s = Some(String::from("a"));
if let Some(ref mut v) = s { v.push('b'); }
s // Some("ab")Inclusive and exclusive ranges in match.
match 5u8 {
0..=9 => "digit",
_ => "other",
} // "digit"Stack versions: Rust 1.97.0 · edition 2024 · Tokio 1.x · serde 1.0
Reviewed by Chris St. John·Last updated Jul 18, 2026