Pattern Matching Basics

Pattern matching allows destructuring and inspecting values using match or if let.

Using match

let value = Some(3);
match value {
    Some(1) => println!("One"),
    Some(2) => println!("Two"),
    Some(n) => println!("Matched number: {}", n),
    None => println!("Nothing"),
}

Using if let

Simplifies matching a single pattern:

let value = Some(5);
if let Some(n) = value {
    println!("Got: {}", n);
}

if let ignores unmatched cases and is ideal for concise control flow.

← PrevNext →