Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created August 21, 2019 00:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/4544a0844014ee22baf24dba677a2366 to your computer and use it in GitHub Desktop.
Save rust-play/4544a0844014ee22baf24dba677a2366 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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