Created
August 21, 2019 00:11
-
-
Save rust-play/136066cee6bfb5e6825186c93d046224 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::fs::File; | |
use std::path::Path; | |
use std::num::ParseIntError; | |
use failure::Fail; | |
fn do_io_things(file: &Path) -> Result<i32, Error> { | |
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, Fail)] | |
enum Error { | |
#[fail(display = "{}", e)] | |
IoFailed { | |
#[fail(cause)] | |
e: io::Error, | |
}, | |
#[fail(display = "{}", e)] | |
ParseIntFailed { | |
#[fail(cause)] | |
e: ParseIntError, | |
}, | |
} | |
impl From<io::Error> for Error { | |
fn from(e: io::Error) -> Error { | |
Error::IoFailed { e } | |
} | |
} | |
impl From<ParseIntError> for Error { | |
fn from(e: ParseIntError) -> Error { | |
Error::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