Input Error handling

I would like to allow the user to enter a user_id to search for. If this block of code was in a loop, would it be possible for a user to just type in a use_id, if it can parse, then it returns the result. Otherwise the user should be shown an error message and allowed to retype the user_id. Is the following code snippet a good approach for solving this situation?

let user_id= match new_input.parse::<usize>() {
            Ok(user_id) => user_id,
            Err(err) => {
                println!("Error: {}", err);
                continue;
            }
        };

Looks like you're on the right track to me. And since loop is an expression which can return a value, you should be able to do something like:

let user_id = loop {
    match new_input.parse::<usize>() {
        Ok(user_id) => break user_id,
        Err(err) => {
            println!("Error: {}", err);
        }
    }
};

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.