Skip to content

Commit

Permalink
Re-order actions you can take with a Result
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
illicitonion committed Oct 31, 2024
1 parent 9e63a5c commit 2e2f6b9
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions book/src/05_ticket_v2/07_unwrap.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,35 @@ 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") {
Ok(number) => println!("Parsed number: {}", number),
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");
```

0 comments on commit 2e2f6b9

Please sign in to comment.