mirror of
https://github.com/rust-lang/book.git
synced 2026-12-04 13:24:55 -06:00
Edit and extract new text for nostarch
This commit is contained in:
@@ -12,3 +12,32 @@ error[E0277]: the `?` operator can only be used in a function that returns
|
||||
= help: the trait `std::ops::Try` is not implemented for `()`
|
||||
= note: required by `std::ops::Try::from_error`
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Then, please replace the highlighted paragraph on page 161 with this text:
|
||||
|
||||
This error points out that we’re only allowed to use the `?` operator in a
|
||||
function that returns `Result<T, E>`. In functions that don’t return `Result<T,
|
||||
E>`, when you call other functions that return `Result<T, E>`, you’ll need to
|
||||
use a `match` or one of the `Result<T, E>` methods to handle the `Result<T, E>`
|
||||
instead of using the `?` operator to potentially propagate the error to the
|
||||
calling code.
|
||||
|
||||
However, we can change how we write the `main` function so that it does return
|
||||
a `Result<T, E>`:
|
||||
|
||||
```
|
||||
use std::error::Error;
|
||||
use std::fs::File;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let f = File::open("hello.txt")?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
The `Box<dyn Error>` type is called a “trait object,” which we’ll talk about in
|
||||
the “Using Trait Objects that Allow for Values of Different Types” section of
|
||||
Chapter 17. For now, you can read `Box<dyn Error>` to mean “any kind of error.”
|
||||
|
||||
@@ -81,7 +81,7 @@ bug in their code so they can fix it during development. Similarly, `panic!` is
|
||||
often appropriate if you’re calling external code that is out of your control
|
||||
and it returns an invalid state that you have no way of fixing.
|
||||
|
||||
However, when failure is expected, it is more appropriate to return a `Result`
|
||||
However, when failure is expected, it's more appropriate to return a `Result`
|
||||
than to make a `panic!` call. Examples include a parser being given malformed
|
||||
data or an HTTP request returning a status that indicates you have hit a rate
|
||||
limit. In these cases, returning a `Result` indicates that failure is an
|
||||
|
||||
Reference in New Issue
Block a user