Created
January 17, 2019 02:55
-
-
Save rust-play/8cebab9c46c2f2b8c375f58b17d25c0c 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::{ | |
error, | |
fmt::{self, Display, Formatter}, | |
io, | |
num::ParseIntError, | |
result, | |
}; | |
#[derive(Debug)] | |
enum Error { | |
Io(io::Error), | |
Parse(ParseIntError), | |
} | |
impl Display for Error { | |
fn fmt(&self, formatter: &mut Formatter) -> fmt::Result { | |
match *self { | |
Error::Io(ref error) => error.fmt(formatter), | |
Error::Parse(ref error) => error.fmt(formatter), | |
} | |
} | |
} | |
impl error::Error for Error {} | |
impl From<io::Error> for Error { | |
fn from(error: io::Error) -> Self { | |
Error::Io(error) | |
} | |
} | |
impl From<ParseIntError> for Error { | |
fn from(error: ParseIntError) -> Self { | |
Error::Parse(error) | |
} | |
} | |
type Result<T> = result::Result<T, Error>; | |
fn main() -> Result<()> { | |
let mut line = String::new(); | |
std::io::stdin().read_line(&mut line)?; | |
let sum = line.split_whitespace() | |
.map(|word| word.parse::<i64>()) | |
.fold(Ok(0), |sum, val| sum.and_then(|s| val.or_else(|e| Err(e)) | |
.and_then(|v| Ok(s + v))))?; | |
println!("Sum: {}", sum); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment