Error matching a range

Here is a snippet of code:

fn main() {
    let min = 1;
    let max = 7;
    let num = 5;

    match num {
        min..=max => println!("\n The number is in range."),

        _ => println!("\n The number is outside the range."),
    }
}

The compiler throws the following error:

error[E0080]: runtime values cannot be referenced in patterns
 --> src/main.rs:9:9
  |
9 |         min..=max => println!("\n The number is in range."),
  |    

I looked up the error code and that didn't help. I really think this code should work, but it doesn't. What am I doing wrong?

The compiler has to be able to reason about the match arm patterns at compile time (and structurally). You can use consts instead of variables.

    const MIN: i32 = 1;
    const MAX: i32 = 7;
    let num = 5;

    match num {
        MIN..=MAX => println!("\n The number is in range."),
        _ => println!("\n The number is outside the range."),
    }

Or if that's not an option, use something besides match.

    if (min..=max).contains(&num) {
        println!("\n The number is in range.");
    } else {
        println!("\n The number is outside the range.");
    }
2 Likes

Okay. I guess I've looked at match statements as a nice, clean alternative to if-else. I need to pass my min and max values to a function where I set up a match statement to deal with them. I'll replace it with an if-else.

So, what is the reasoning behind match having this limitation?

Exhaustiveness checking (proving every match covers all possible values) is the main one.

I guess that makes sense. Thanks for the help.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.