typestar

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

  1. The else block must return, break or panic.
  2. After it, the binding is available unwrapped.
  3. It flattens the nesting that if let would add.

Keywords and builtins used here

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.

Type this snippet

Step 6 of 8 in Control flow, step 16 of 39 in Language basics.

← Previous Next →