1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-16 19:14:20 +02:00

Remove nesting from let else example (#2600)

This commit is contained in:
Nicole L
2025-02-11 10:45:04 -08:00
committed by GitHub
parent d732821edb
commit 699c5137c7

View File

@ -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() {
@ -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
@ -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>