Matching Error (Outside of Loop) when replace Return with Continue

When the code snippet is used with a hard-coded input value of "4" or "4\n", then the result of match will be Ok (since the trim() function removes the line break \n) and subsequent code will run without the program exiting.

However, if I substitute the value of "4" with an incorrect type such as "a" (of type String) or "-1" (since it has been defined to only accept u32 positive integers) then the match will be Err and the program will exit without processing any subsequent code.

use std::old_io;

fn main() {

    println!("Enter your name...");

    //let input = old_io::stdin().read_line().ok().expect("Failed to read line"); 
    let input = "4";

    let input_num: Result<u32, _> = input.trim().parse();

    let unwrapped_num = match input_num {
        Ok(unwrapped_num) => unwrapped_num,
        Err(_) => {
            println!("Please input a number!");
            continue;
        }
    };
}

Why is it that if I replace return with continue instead within the Err block, it gives an error?

src/main.rs:72:20: 72:21 error: `continue` outside of loop [E0268]
1 Like

You can only use continue inside a loop, such as loop, while or for. You could try putting the whole "getting input" stuff into its own function, wrap the code with an infinite loop { } and return the result on success.

2 Likes

Thanks for your response, that worked a treat. I have been following the Guessing Game exercise of the Rust Language Book and they mentioned using a loop but I completely overlooked implementing it.