Rust Pattern Matching

Powerful pattern matching with match and if let

Match Expression

let number = 7;
match number { # match value
    1 => println!("One"),
    2 | 3 | 5 | 7 => println!("Prime"), # multiple patterns
    4..=10 => println!("Range"), # range pattern
    _ => println!("Other"), # catch all
}

If Let

let some_value = Some(3);
if let Some(x) = some_value { # destructure if matches
    println!("{}"{}, x);
} else {
    println!("None");
}

While Let

let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() { # loop while pattern matches
    println!("{}"{}, top);
}

Destructuring Structs

struct Point { x: i32, y: i32 }
let p = Point { x: 0, y: 7 };
match p {
    Point { x, y: 0 } => println!("On x axis at {}"{}, x),
    Point { x: 0, y } => println!("On y axis at {}"{}, y),
    Point { x, y } => println!("({}, {})"{}, x, y),
}