Skip to content
Rust

Pattern Matching

match and destructuring.

By EZ4Code Team
matchpattern-matching

Code

fn main() {
    let value = 3;

    // Basic match
    match value {
        1 => println!("one"),
        2 | 3 => println!("two or three"),
        4..=10 => println!("four to ten"),
        _ => println!("other"),
    }

    // Destructure struct
    struct Point { x: i32, y: i32 }
    let p = Point { x: 1, y: 2 };
    match p {
        Point { x: 0, y: 0 } => println!("origin"),
        Point { x, y: 0 } => println!("on x axis: {}", x),
        Point { x: 0, y } => println!("on y axis: {}", y),
        Point { x, y } => println!("({}, {})", x, y),
    }

    // Destructure tuple
    let (a, b, c) = (1, 2, 3);
    println!("{} {} {}", a, b, c);

    // Destructure enum
    let opt = Some(5);
    if let Some(n) = opt {
        println!("got: {}", n);
    }

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

Explanation

Pattern matching destructures data via match, if let, while let, supporting range, or, binding patterns.

More Rust Snippets