mirror of
https://github.com/mainmatter/100-exercises-to-learn-rust
synced 2024-12-26 21:58:49 +01:00
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.
This commit is contained in:
parent
9e63a5cdf6
commit
2e2f6b945d
1 changed files with 24 additions and 9 deletions
|
@ -21,16 +21,8 @@ let number = parse_int("42") + 2;
|
||||||
|
|
||||||
## You got a `Result`. Now what?
|
## 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.
|
- Destructure the `Result` using a `match` expression to deal with the error case explicitly.
|
||||||
```rust
|
```rust
|
||||||
match parse_int("42") {
|
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),
|
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");
|
||||||
|
```
|
||||||
|
|
Loading…
Reference in a new issue