statement

Rust Exit early when a pattern fails

Use let-else to extract data and handle failure before the remaining work. The else branch must diverge, for example by returning from the function. Expected output (not executed): count: 3 missing Why: The successful binding remains available after the statement; the missing case returns early. Common mistake: An else block that merely prints and then continues is invalid here.

Formal Syntax & Structure

rust syntaxrust
let pattern = value else { return; };

Working Example

Example Snippetrust
fn report(value: Option<i32>) {    let Some(count) = value else {        println!("missing");        return;    };    println!("count: {count}");}
fn main() {    report(Some(3));    report(None);}
Rust Reference