Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 17, 2019 02:55
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/8cebab9c46c2f2b8c375f58b17d25c0c to your computer and use it in GitHub Desktop.
Save rust-play/8cebab9c46c2f2b8c375f58b17d25c0c to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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