← Back to Rust Course | Chapter 8: Enums & Pattern Matching | Lesson 3 of 7

Match Arms in Depth

Match arms are the different answers you write for each possible shape a value could take.

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

markup
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),
    }
}

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

markup
fn main() {
    let score = 82;
    match score {
        90..=100 => println!("A"),
        80..=89 => println!("B"),
        70..=79 => println!("C"),
        _ => println!("Below C"),
    }
}

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

markup
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"),
    }
}

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

markup
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"),
    }
}
Common Mistakes
  1. Ordering match arms so a broad pattern (like a range) accidentally shadows a more specific one listed after it.
  2. Forgetting a match guard (if condition) can add extra conditions onto a pattern for finer-grained control.
  3. Not realizing bound variables in a match arm, like n in Some(n) =>, are only valid within that specific arm.
Chapter Summary
  • Each match arm pairs a pattern with the code to run when that pattern matches.
  • Range patterns like 1..=5 match any value within an inclusive range.
  • Match guards add an extra if condition to 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.