Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove nesting from let else example #2600

Merged
merged 3 commits into from
Feb 11, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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>