1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-01-05 16:10:31 +02:00

Implement Error.

This commit is contained in:
Andrew Walbran 2023-01-16 17:53:43 +00:00
parent caaca140ca
commit 27b6165202

View File

@ -19,8 +19,10 @@ The `From::from` call here means we attempt to convert the error type to the
type returned by the function:
```rust,editable
use std::error::Error;
use std::{fs, io};
use std::io::Read;
use std::fmt::{self, Display, Formatter};
#[derive(Debug)]
enum ReadUsernameError {
@ -28,6 +30,17 @@ enum ReadUsernameError {
EmptyUsername(String),
}
impl Error for ReadUsernameError {}
impl Display for ReadUsernameError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::IoError(e) => write!(f, "IO error: {}", e),
Self::EmptyUsername(filename) => write!(f, "Found no username in {}", filename),
}
}
}
impl From<io::Error> for ReadUsernameError {
fn from(err: io::Error) -> ReadUsernameError {
ReadUsernameError::IoError(err)