Match and destructuring
Quick answer
Pattern matching can inspect the shape of a value and bind parts of it. With enums and structs, this lets you select a branch and obtain its data in one operation.
Exhaustiveness, guards and ownership
A match must cover every possible input. A guard such as if amount > 0 further restricts a pattern, so an unguarded fallback remains necessary. Matching an owned value may move non-Copy fields into bindings; matching a borrowed value can bind references instead. Use _ to ignore a value without giving it a binding.
fn main() { let amount = 5; let label = match amount { n if n > 0 => "positive", 0 => "zero", _ => "negative", }; println!("{label}");}Expected stdout (not executed):
positiveThe first successful pattern and guard determine the result.
enum Message { Text(String), Quit }fn main() { let message = Message::Text(String::from("hello")); match &message { Message::Text(text) => println!("{text}"), Message::Quit => println!("quit"), } match &message { Message::Text(text) => println!("bytes: {}", text.len()), Message::Quit => println!("quit"), } let _quit = Message::Quit;}Expected stdout (not executed):
hellobytes: 5Both matches borrow the enum, so its owned String remains usable.
Common mistake
Do not assume a guarded arm covers every instance of its pattern. Provide an appropriate unguarded case.
Try it yourself
Create a match for a temperature: below zero, exactly zero and above zero; use a guard and an exhaustive fallback.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Match and destructuring — practice quiz
Choose one answer per question, then review the explanation.
Why is a guarded pattern `n if n > 0` insufficient on its own for matching an i32?
What does `_` do as a standalone pattern?
How can you match a data-carrying enum without moving its owned String field?