let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
this code is from Advanced Types - The Rust Programming Language
when i copy this code into rustrover, the ide tells me compile error: "continue can obly be used inside a loop/while block".
WHY?
Uhm. Because you've just copied the code without making sure it is, in fact, inside of a loop
or a while
block? The snippet in question is from 2-5 (as per "recall the code from Listing 2-5" part):
loop {
// ...
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
// it's here that that the `match guess.trim().parse()` + `continue` goes
}
Without a loop to "continue", you can't continue.
"continue" means go back to the start of the loop and run the loop again. If in a "while" loop you go back to the start of loop and check the condition of the "while" before looping.
If you are not in a loop, there is nowhere to continue.
This is one of those strange cases where a "match" can have arms that are of different types.
Nit: All the arms have the same type. !
has special coercion abilities and coerces to the type of the other arms.
2 Likes