How to use values from an array in matching ranges of values with ..= in rust?

I'm learning rust and I found something I can't just find in google. I was experimenting with match and I wanted to use values from an array with the ..= syntax. I know I'm doing something wrong, but I only know Js and Python and I feel I'm missing something basic that it's just known but not explained.

    pub fn match_statement() {
    println!("Match statement----------------------------------");
    let mut country_code=0;
    let country_codes_range: [i64; 4] = [1,999,50,66];
    let country = match country_code {
        34 => "Spain",
        46 => "Sweden",
        country_codes_range[0]..=country_codes_range[1] => "unknown",
        _ => "invalid",
    };
    country_code=invalid_country;
    println!(
        "The {} country code is {} because is out of the range [{},{}]",
        country, invalid_country, country_codes_range[0], country_codes_range[1]
    );
}

the error I get is: expected one of =>, @, if, or |, found [ on the line country_codes_range[0]..=country_codes_range[1] => "unknown"

I don't know if the issue lies in my calling of items of the array, an incorrect use of ..= or another thing

Also, I guess I would get a similar error if I used a tuple instead of an array?

Thanks for your help

Upvotes: 0

Views: 1507

Answers (1)

cameron1024
cameron1024

Reputation: 10156

Rust needs to know the "values" of each match arm at compile time, so what you're describing isn't possible, instead you'll get an error saying runtime values cannot be references in patterns.

If you know what country_codes_range will be at compile time, you can make it available at compile time using const:

fn match_statement() {
  let country_code = 123;

  const COUNTRY_CODES_RANGE: [i64; 4] = [1, 999, 50, 66];
  const FIRST: i64 = COUNTRY_CODES_RANGE[0];
  const SECOND: i64 = COUNTRY_CODES_RANGE[1];

  let country = match country_code {
    34 => "spain",
    46 => "sweden",
    FIRST..=SECOND => "unknown",
    _ => "invalid",
  };
  
  // ...
}

Note, the intermediate consts FIRST and SECOND are needed because currently Rust's parser doesn't support the a[i] syntax in patterns, though that is a separate problem to having a match use runtime values

Upvotes: 2

Related Questions