Rust by example - Control Flow: Match

1 minute read


:information_source: Note: Read the offical references to get the most updated information.

Control Flow: match

Rust provides pattern matching with match, which can be used like a C switch. The first matching arm is evaluated and all possible values must be covered.

fn main() {
    let number = 13;

    match number {
        // Match a single value
        1 => println!("One!"),
        // Match several values
        2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
        // Match an inclusive range
        13..=19 => println!("A teen"),
        // Handle the rest of cases
        _ => println!("Ain't special"),
    } // Tell me about 13

    let boolean = true;
    // Match is an expression too
    let binary = match boolean {
        // The arms of a match must cover all the possible values
        false => {
            println!("zero!");
            0
        },
        true => 1,
    };

    println!("{} -> {}", boolean, binary); // true -> 1
}

Bind to Values

Another useful feature of match arms is that they can bind to the parts of the values that match the pattern. This is how we can extract values out of enum variants, as in the s with "Hello world" below.

When using non-copyable data we should take care with Ownership

fn main() {
let opt: Option<String> =
    Some(String::from("Hello world"));

// opt became &opt
match &opt {
    Some(s) => println!("Some: {}", s),
    None => println!("None!")
};

println!("{:?}", opt);
}
// Some: Hello world
// Some("Hello world")

Note that took the reference of opt and not the value. Rust will “push down” the reference from the outer enum, &Option<String>, to the inner field, &String. Therefore s has type &String, and opt can be used after the match.

References

Updated:

Leave a Comment