diff --git a/src/pattern-matching/let-control-flow/let-else.md b/src/pattern-matching/let-control-flow/let-else.md index aceef48e5f8f..f405c6816986 100644 --- a/src/pattern-matching/let-control-flow/let-else.md +++ b/src/pattern-matching/let-control-flow/let-else.md @@ -7,20 +7,25 @@ off the end of the block). ```rust,editable fn hex_or_die_trying(maybe_string: Option) -> Result { - // 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() { ```
- -`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) -> Result { } ``` +## 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 `?`. +