Match Arms in Depth
In this page:
Binding Values in Match Arms
A match arm's pattern can bind part of the matched value to a new variable, making that data available only within that specific arm's code.
Example: Binding Values in Match Arms
enum Message {
Text(String),
Number(i32),
}
fn main() {
let msg = Message::Number(42);
match msg {
Message::Text(s) => println!("Text: {}", s),
Message::Number(n) => println!("Number: {}", n),
}
}
Login to try C/C++/Java/PHP code in the editor
Matching Ranges
A pattern can match an inclusive range of values using start..=end, which is more concise than listing every individual value or writing a separate if chain.
Example: Matching Ranges
fn main() {
let score = 82;
match score {
90..=100 => println!("A"),
80..=89 => println!("B"),
70..=79 => println!("C"),
_ => println!("Below C"),
}
}
Login to try C/C++/Java/PHP code in the editor
Match Guards
A match guard adds an extra if condition after a pattern, letting an arm only match when both the pattern and the extra condition are true.
Example: Match Guards
fn main() {
let pair = (4, -4);
match pair {
(x, y) if x == -y => println!("These are opposites"),
(x, y) if x == y => println!("These are equal"),
_ => println!("No special relationship"),
}
}
Login to try C/C++/Java/PHP code in the editor
Combining Multiple Patterns in One Arm
The | operator can combine several patterns, including ranges, into a single arm so related cases share one block of code.
Example: Combining Multiple Patterns in One Arm
fn main() {
let ch = '7';
match ch {
'0'..='9' => println!("It is a digit"),
'a'..='z' | 'A'..='Z' => println!("It is a letter"),
_ => println!("Something else"),
}
}
Login to try C/C++/Java/PHP code in the editor
- Ordering match arms so a broad pattern (like a range) accidentally shadows a more specific one listed after it.
- Forgetting a match guard (
if condition) can add extra conditions onto a pattern for finer-grained control. - Not realizing bound variables in a match arm, like
ninSome(n) =>, are only valid within that specific arm.
- Each match arm pairs a pattern with the code to run when that pattern matches.
- Range patterns like
1..=5match any value within an inclusive range. - Match guards add an extra
if conditionto a pattern for more precise matching. - Bound variables introduced by a pattern (like extracting data from an enum) are scoped to their arm.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: