|
| 1 | +# let-else |
| 2 | + |
| 3 | + |
| 4 | +> 🛈 stable since: rust 1.65 |
| 5 | +
|
| 6 | + |
| 7 | +With `let`-`else`, a refutable pattern can match and bind variables |
| 8 | +in the surrounding scope like a normal `let`, or else diverge (e.g. `break`, |
| 9 | +`return`, `panic!`) when the pattern doesn't match. |
| 10 | + |
| 11 | +```rust |
| 12 | +fn get_count_item(s: &str) -> (u64, &str) { |
| 13 | + let mut it = s.split(' '); |
| 14 | + let (Some(count_str), Some(item)) = (it.next(), it.next()) else { |
| 15 | + panic!("Can't segment count item pair: '{s}'"); |
| 16 | + }; |
| 17 | + let Ok(count) = u64::from_str(count_str) else { |
| 18 | + panic!("Can't parse integer: '{count_str}'"); |
| 19 | + }; |
| 20 | + (count, item) |
| 21 | +} |
| 22 | +assert_eq!(get_count_item("3 chairs"), (3, "chairs")); |
| 23 | +``` |
| 24 | + |
| 25 | +The scope of name bindings is the main thing that makes this different from |
| 26 | +`match` or `if let`-`else` expressions. You could previously approximate these |
| 27 | +patterns with an unfortunate bit of repetition and an outer `let`: |
| 28 | + |
| 29 | +```rust |
| 30 | + let (count_str, item) = match (it.next(), it.next()) { |
| 31 | + (Some(count_str), Some(item)) => (count_str, item), |
| 32 | + _ => panic!("Can't segment count item pair: '{s}'"), |
| 33 | + }; |
| 34 | + let count = if let Ok(count) = u64::from_str(count_str) { |
| 35 | + count |
| 36 | + } else { |
| 37 | + panic!("Can't parse integer: '{count_str}'"); |
| 38 | + }; |
| 39 | +``` |
| 40 | + |
| 41 | +### See also: |
| 42 | + |
| 43 | +[option][option], [match][match], [if let][if_let] and the [let-else RFC][let_else_rfc]. |
| 44 | + |
| 45 | + |
| 46 | +[match]: ./match.md |
| 47 | +[if_let]: ./if_let.md |
| 48 | +[let_else_rfc]: https://rust-lang.github.io/rfcs/3137-let-else.html |
| 49 | +[option]: ../std/option.md |
0 commit comments