Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a `continue` in a match arm not have to typecheck?

Tags:

types

rust

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?

like image 947
wopwop Avatar asked Feb 04 '23 20:02

wopwop


1 Answers

However, the Err(_) branch returns continue

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.

like image 82
Shepmaster Avatar answered Feb 08 '23 16:02

Shepmaster