let else in Rust
let else binds on the happy path and forces the failure branch to diverge.
fn parse_port(text: &str) -> u16 {
let Ok(port) = text.parse::<u16>() else {
println!("not a port: {text}");
return 8080;
};
port
}
fn main() {
println!("{}", parse_port("9000"));
println!("{}", parse_port("http"));
}
How it works
- The
elseblock must return, break or panic. - After it, the binding is available unwrapped.
- It flattens the nesting that
if letwould add.
Keywords and builtins used here
Okelsefnletmainparse_portreturnstru16
The run, in numbers
- Lines
- 12
- Characters to type
- 218
- Tokens
- 77
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 54 seconds.
Step 6 of 8 in Control flow, step 16 of 39 in Language basics.