From 2e2f6b945dece8e6b3706f50722fa1774aa17944 Mon Sep 17 00:00:00 2001 From: Daniel Wagner-Hall Date: Thu, 31 Oct 2024 13:45:28 +0000 Subject: [PATCH] Re-order actions you can take with a Result It's generally better practice to handle or propagate errors, rather than panicking in response to them. This edit moves panicking to be the _last_ option introduced, rather than the first. It also adds caveats to avoid doing so, and explicitly mentions propagating as something to consider. --- book/src/05_ticket_v2/07_unwrap.md | 33 ++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/book/src/05_ticket_v2/07_unwrap.md b/book/src/05_ticket_v2/07_unwrap.md index ba67eed..4088c1d 100644 --- a/book/src/05_ticket_v2/07_unwrap.md +++ b/book/src/05_ticket_v2/07_unwrap.md @@ -21,16 +21,8 @@ let number = parse_int("42") + 2; ## You got a `Result`. Now what? -When you call a function that returns a `Result`, you have two key options: +When you call a function that returns a `Result`, you have three key options: -- Panic if the operation failed. - This is done using either the `unwrap` or `expect` methods. - ```rust - // Panics if `parse_int` returns an `Err`. - let number = parse_int("42").unwrap(); - // `expect` lets you specify a custom panic message. - let number = parse_int("42").expect("Failed to parse integer"); - ``` - Destructure the `Result` using a `match` expression to deal with the error case explicitly. ```rust match parse_int("42") { @@ -38,3 +30,26 @@ When you call a function that returns a `Result`, you have two key options: Err(err) => eprintln!("Error: {}", err), } ``` +- Propagate the error. If you're in a function which also returns a `Result`, you can use the `?` operator to early-return an error if it occurred: + ```rust + let number = parse_int("42")?; + println!("Parsed number: {}", number); + ``` + + The `?` operator works the same as manually destructuring the result and early returning: + ```rust + let number = match parse_int("42") { + Ok(number) => number, + Err(err) => return Err(err), + }; + println!("Parsed number: {}", number); + ``` +- Panic if the operation failed.\ + This is done using either the `unwrap` or `expect` methods.\ + This this should generally only be done in your top-level `main` function - most functions should propagate errors rather than panic. + ```rust + // Panics if `parse_int` returns an `Err`. + let number = parse_int("42").unwrap(); + // `expect` lets you specify a custom panic message. + let number = parse_int("42").expect("Failed to parse integer"); + ```