I want to use the condition of the match statement in Rust to do 0... =a+5

Viewed 1155

want to do

I would like to use Rust's match statement to process variables differently when they are in an arbitrary range and in other cases. In that case, the code would look like this.

Applicable codes

// idx is usize variable
// num is usize variabel

let res: Option<f64> = match idx {
    1..=num-5 => {
        Some(func())
    },
    _ => None,
};

Error I received.

error: expected one of `::`, `=>`, `if`, or `|`, found `-`
  --> src/features.rs:34:22
   |
34 |         1..=num-5 => Some(func()),
   |            ^ expected one of `::`, `=>`, `if`, or `|`


2 Answers

You can check the dynamic range over a match guard:

fn main() {
    let idx = 6;
    let num = 15;
    let res = match idx {
        n if (1..=num - 5).contains(&n) => Some("foo"),
        _ => None,
    };
    println!("{:?}", res);
}

Playground

Runtime values cannot be referenced in patterns. Also you cannot make operations.

Use const instead

const num :i32 = 19 - 5;

let res: Option<f64> = match idx {
    1..=num => {
        Some(func())
    },
    _ => None,
};
Related