rustpattern-matching

How do I match based on a dynamic variable?


Is it possible to match on a dynamic variable instead of only literals?

In this code, the first match should do the same as the commented out match (number[0] being 0 and number[1] being 1):

const NUMBERS: [i8; 2] = [0, 1];

fn test() {
    let current = 5;

    let string = match current % 2 {
        NUMBERS[0] => "even", // This does not work
        NUMBERS[1] => "odd",  // This does not work
        _ => unreachable!(),
    };

    // let string = match current % 2 {
    //     0 => "even",
    //     1 => "odd",
    //     _ => unreachable!()
    // };
}

Solution

  • You can use Match guards.

    let string = match current % 2 {
        even if even == numbers[0] => "even",
        odd if odd == numbers[1] => "odd",
        _ => unreachable!()
    };