Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thanks for your help

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading