21.15 The let else
Construct (Rust 1.65+)
Rust 1.65 introduced let else
, which allows a refutable pattern in a let
binding. If the pattern match fails, an else
block runs and must diverge (e.g., via return
or panic!
). Otherwise, the matched bindings are available in the surrounding scope:
fn process_value(opt: Option<i32>) { let Some(val) = opt else { println!("No value provided!"); return; }; // If we reach this line, opt matched Some(val). println!("Got value: {}", val); } fn main() { process_value(None); process_value(Some(42)); }
Here, Some(val)
is refutable. If opt
is None
, the else
block executes and must end the current function (or loop). If opt
is Some(...)
, the binding val
is introduced into the parent scope.