1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-01-20 21:18:26 +02:00

Mention std::error::Error in speaker notes, and other useful traits.

This commit is contained in:
Andrew Walbran 2023-01-16 17:37:00 +00:00
parent 5dd87192e8
commit 52d28b155b
2 changed files with 16 additions and 1 deletions

View File

@ -57,4 +57,9 @@ Key points:
* The `username` variable can be either `Ok(string)` or `Err(error)`.
* Use the `fs::write` call to test out the different scenarios: no file, empty file, file with username.
It is good practice for all error types to implement `std::error::Error`, which requires `Debug` and
`Display`. It's generally helpful for them to implement `Clone` and `Eq` too where possible, to make
life easier for tests and consumers of your library. In this case we can't easily do so, because
`io::Error` doesn't implement them.
</details>

View File

@ -8,7 +8,7 @@ use std::{fs, io};
use std::io::Read;
use thiserror::Error;
#[derive(Error, Debug)]
#[derive(Debug, Error)]
enum ReadUsernameError {
#[error("Could not read: {0}")]
IoError(#[from] io::Error),
@ -33,3 +33,13 @@ fn main() {
}
}
```
<details>
`thiserror`'s derive macro automatically implements `std::error::Error`, and optionally `Display`
(if the `#[error(...)]` attributes are provided) and `From` (if the `#[from]` attribute is added).
It also works for structs.
It doesn't affect your public API, which makes it good for libraries.
</details>