Last active
February 8, 2019 18:45
-
-
Save nyinyithann/cd991a3f4c7837baee6002d4440e4569 to your computer and use it in GitHub Desktop.
composition of functions of Result<T,E>
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::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