Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!()
    // };
}
like image 784
Teiem Avatar asked Mar 22 '26 08:03

Teiem


1 Answers

You can use Match guards:

let string = match current % 2 {
    even if even == numbers[0] => "even",
    odd if odd == numbers[1] => "odd",
    _ => unreachable!()
};
like image 199
Abdul Niyas P M Avatar answered Mar 24 '26 23:03

Abdul Niyas P M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!