Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created August 21, 2019 00:11
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/136066cee6bfb5e6825186c93d046224 to your computer and use it in GitHub Desktop.
Save rust-play/136066cee6bfb5e6825186c93d046224 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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