Skip to content

Commit 246f9e6

Browse files
committed
Add documentation for let-else.
Text mostly copied from https://blog.rust-lang.org/2022/11/03/Rust-1.65.0.html#let-else-statements.
1 parent 2b15c0a commit 246f9e6

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
- [Guards](flow_control/match/guard.md)
6060
- [Binding](flow_control/match/binding.md)
6161
- [if let](flow_control/if_let.md)
62+
- [let-else](flow_control/let_else.md)
6263
- [while let](flow_control/while_let.md)
6364

6465
- [Functions](fn.md)

src/flow_control/let_else.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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

Comments
 (0)