Created
August 21, 2019 00:07
-
-
Save rust-play/4544a0844014ee22baf24dba677a2366 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
use std::io::Read; | |
use std::fmt; | |
use std::error::Error; | |
use std::fs::File; | |
use std::path::Path; | |
use std::num::ParseIntError; | |
fn do_io_things(file: &Path) -> Result<i32, MyError> { | |
let mut file = File::open(file)?; | |
let mut contents = String::new(); | |
file.read_to_string(&mut contents)?; | |
let num = contents.parse()?; | |
Ok(num) | |
} | |
#[derive(Debug)] | |
enum MyError { | |
IoFailed { | |
e: io::Error, | |
}, | |
ParseIntFailed { | |
e: ParseIntError, | |
}, | |
} | |
impl Error for MyError { | |
fn source(&self) -> Option<&(dyn Error + 'static)> { | |
match self { | |
MyError::IoFailed { e } => Some(e), | |
MyError::ParseIntFailed { e } => Some(e), | |
} | |
} | |
} | |
impl fmt::Display for MyError { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
match self { | |
MyError::IoFailed { e } => write!(f, "{}", e), | |
MyError::ParseIntFailed { e } => write!(f, "{}", e), | |
} | |
} | |
} | |
impl From<io::Error> for MyError { | |
fn from(e: io::Error) -> MyError { | |
MyError::IoFailed { e } | |
} | |
} | |
impl From<ParseIntError> for MyError { | |
fn from(e: ParseIntError) -> MyError { | |
MyError::ParseIntFailed { e } | |
} | |
} | |
fn main() { | |
let file = Path::new("number.txt"); | |
match do_io_things(&file) { | |
Ok(num) => println!("the number is {}", num), | |
Err(e) => println!("{}", e), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment