Reputation: 151
Rust's guessing game tutorial has the following example code:
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
The result of the match should be u32
and this is the case in the Ok(num)
branch. However, the Err(_)
branch returns continue
, which is certainly not a u32
. Why does this typecheck and work?
Upvotes: 4
Views: 131
Reputation: 431689
However, the
Err(_)
branch returnscontinue
Not really. continue
is not something that "returns", it's something that changes the flow of code. Since that match arm does not produce a value, the type of it doesn't matter. The match
as a whole does typecheck - every resulting value is a u32
.
You can also use other control flow keywords like return
or break
.
A similar concept is divergent functions. These are functions that are guaranteed to never return, so they can be used in place of any expression.
This allows you to also use macros like panic!("...")
or unimplemented!()
as a match arm, as these expand to a diverging function.
Upvotes: 8