Help, match in range

HI, THIS PIECE GIVE ME ERROR: error[E0080]: runtime values cannot be referenced in patterns
0 ..= genre_vector_len => {
| ^^^^^^^^^^^^^^^^

use std::{fs, io};
use std::path::Path;
use std::str::FromStr;

fn main() -> io::Result<()> {        
    // .variables
    let genre_vector = vec!["book1","book3","book2","book5"];

    loop {
        // .print list from genre_vector
        for (i, gen) in genre_vector.iter().enumerate() {
            println!("[{}] {} ", i, gen);
        // .reading from keyboard
        let mut input = String::new();
        let stdin_preset = io::stdin();
        stdin_preset.read_line(&mut input);
        let genre_vector_len = genre_vector.len() as u32;
        let input:u32 = input.trim().parse().expect("Please type a number!");
        match input {
            0 ..= genre_vector_len => { // error[E0080]: runtime values cannot be referenced in patterns
                println!("Correct Input!");
            _ => println!("Incorrect. Choice 0-{}", genre_vector_len),
        } // end m1            
    } // end loop

well, the compiler error says what it means: you can't use a variable in a pattern, you can only use compile time constant.

there's alternative ways to your problem, the most obvious one: just use conditional branch:

if input <= genre_vector_len {
} else {

checking an index in range, I assume you are going to use the element of the vector anyway, so instead of this:

if index < v.len() {
    let x = v[index];
    // do something with the element
} else {
    // out of bounds error handling

you should use the Vec::get() method, which does the check for you and returns an Option:

if let Some(x) = v.get(index) {
    // do something with x
} else {
    // error handling

since Vec::get() returns an Option, you have many other choices too, like the ? operator, the ok_or() combinator, the if else statement, etc:

// monadic binding inside a function which returns an `Option`
let x = v.get(index)?;
// normal calculation follows

// fail fast using `let else`
let Some(x) = v.get(index) else {
    bug_check!("out of bound index: {}", index);
1 Like

Thanks. :hugs:
i continue the practice using match pattern.

Rust is hard technically, but i understand a little. :thinking:

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.