Rust Tuples Matching tuple values


Example

Rust programs use pattern matching extensively to deconstruct values, whether using match, if let, or deconstructing let patterns. Tuples can be deconstructed as you might expect using match

fn foo(x: (&str, isize, bool)) {
    match x {
        (_, 42, _) => println!("it's 42"),
        (_, _, false) => println!("it's not true"),
        _ => println!("it's something else"),
    }
}

or with if let

fn foo(x: (&str, isize, bool)) {
    if let (_, 42, _) = x {
        println!("it's 42");
    } else {
        println!("it's something else");
    }
}

you can also bind inside the tuple using let-deconstruction

fn foo(x: (&str, isize, bool)) {
    let (_, n, _) = x;
    println!("the number is {}", n);
}