0Pricing
Learn Rust Coding · Lesson

Match Guards and Bindings

Add conditions and capture values.

What Is a Match Guard?

A match guard is an extra if condition added to a match arm. The arm only fires when the pattern matches and the condition is true.

It lets you split one variant into finer cases based on its data.

match number {
    Some(n) if n > 0 => println!("positive"),
    Some(n) => println!("zero or negative"),
    None => println!("no number"),
}

Guard Syntax

Write the pattern, then if condition, then =>. The condition can use any variables the pattern bound.

If the guard is false, Rust moves on to try the next arm.

fn main() {
    let n = 4;
    match n {
        x if x % 2 == 0 => println!("even"),
        _ => println!("odd"),
    }
}

All lessons in this course

  1. Defining Your First Enum
  2. Matching on Enum Variants
  3. Enums with Data
  4. Match Guards and Bindings
← Back to Learn Rust Coding