Skip to content

Commit

Permalink
Remove nesting from let else example (#2600)
Browse files Browse the repository at this point in the history
  • Loading branch information
randomPoison authored Feb 11, 2025
1 parent d732821 commit 699c513
Showing 1 changed file with 26 additions and 18 deletions.
44 changes: 26 additions & 18 deletions src/pattern-matching/let-control-flow/let-else.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,25 @@ off the end of the block).

```rust,editable
fn hex_or_die_trying(maybe_string: Option<String>) -> Result<u32, String> {
// TODO: The structure of this code is difficult to follow -- rewrite it with let-else!
if let Some(s) = maybe_string {
if let Some(first_byte_char) = s.chars().next() {
if let Some(digit) = first_byte_char.to_digit(16) {
Ok(digit)
} else {
Err(String::from("not a hex digit"))
}
} else {
Err(String::from("got empty string"))
}
let s = if let Some(s) = maybe_string {
s
} else {
Err(String::from("got None"))
}
return Err(String::from("got None"));
};
let first_byte_char = if let Some(first) = s.chars().next() {
first
} else {
return Err(String::from("got empty string"));
};
let digit = if let Some(digit) = first_byte_char.to_digit(16) {
digit
} else {
return Err(String::from("not a hex digit"));
};
Ok(digit)
}
fn main() {
Expand All @@ -29,11 +34,6 @@ fn main() {
```

<details>

`if-let`s can pile up, as shown. The `let-else` construct supports flattening
this nested code. Rewrite the awkward version for students, so they can see the
transformation.

The rewritten version is:

```rust
Expand All @@ -54,4 +54,12 @@ fn hex_or_die_trying(maybe_string: Option<String>) -> Result<u32, String> {
}
```

## More to Explore

- This early return-based control flow is common in Rust error handling code,
where you try to get a value out of a `Result`, returning an error if the
`Result` was `Err`.
- If students ask, you can also demonstrate how real error handling code would
be written with `?`.

</details>

0 comments on commit 699c513

Please sign in to comment.