Referring to matched value in Rust

You can bind the pattern to a name:

fn non_zero_rand() -> i32 {
    match rand() {
        0 => 1, // 0 is a refutable pattern so it only matches when it fits.
        x => x, // the pattern is x here,
                // which is non refutable, so it matches on everything
                // which wasn't matched already before
    }
}

A match arm that consists of just an identifier will match any value, declare a variable named as the identifier, and move the value to the variable. For example:

match rand() {
    0 => 1,
    x => x * 2,
}

A more general way to create a variable and match it is using the @ pattern:

match rand() {
    0 => 1,
    x @ _ => x * 2,
}

In this case it is not necessary, but it can come useful when dealing with conditional matches such as ranges:

match code {
    None => Empty,
    Some(ascii @ 0..=127) => Ascii(ascii as u8),
    Some(latin1 @ 160..=255) => Latin1(latin1 as u8),
    _ => Invalid
}

Tags:

Match

Rust