mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-05-16 23:55:42 +02:00
Mention std::error::Error in speaker notes, and other useful traits.
This commit is contained in:
parent
5dd87192e8
commit
52d28b155b
@ -57,4 +57,9 @@ Key points:
|
|||||||
* The `username` variable can be either `Ok(string)` or `Err(error)`.
|
* 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.
|
* 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>
|
</details>
|
||||||
|
@ -8,7 +8,7 @@ use std::{fs, io};
|
|||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
#[derive(Debug, Error)]
|
||||||
enum ReadUsernameError {
|
enum ReadUsernameError {
|
||||||
#[error("Could not read: {0}")]
|
#[error("Could not read: {0}")]
|
||||||
IoError(#[from] io::Error),
|
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>
|
||||||
|
Loading…
x
Reference in New Issue
Block a user