Skip to content

Instantly share code, notes, and snippets.

@nyinyithann
Last active February 8, 2019 18:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyinyithann/cd991a3f4c7837baee6002d4440e4569 to your computer and use it in GitHub Desktop.
Save nyinyithann/cd991a3f4c7837baee6002d4440e4569 to your computer and use it in GitHub Desktop.
composition of functions of Result<T,E>
use std::io;
use std::io::prelude::*;
fn main() {
loop {
let r = get_input("Enter the first number: ")
.and_then(|x| get_input("Enter the second number: ")
.and_then(|y| get_input("Enter the third number: ")
.and_then(|z| Ok(x + y + z))));
if r.is_ok() {
println!("The result is {}.", r.unwrap());
break;
}
}
}
fn get_input(msg: &str) -> Result<i32, io::Error> {
let mut buffer = String::new();
print!("{}", msg);
io::stdout().flush().unwrap();
let stdin = io::stdin();
let mut handle = stdin.lock();
handle.read_line(&mut buffer).and_then(|_| {
buffer
.trim()
.parse::<i32>()
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment