Rust-Programming-Cookbook/Chapter06/sample_map_result.rs

41 wiersze
1.1 KiB
Rust
Czysty Zwykły widok Historia

2017-07-31 06:59:18 +00:00
//-- #########################
//-- Task: Implementing mapt for Result
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 26 March 17
//-- #########################
use std::num::ParseIntError;
// With the return type rewritten, we use pattern matching without `unwrap()`.
fn double_number(number_str: &str) -> Result<i32, ParseIntError> {
match number_str.parse::<i32>() {
Ok(n) => Ok(2 * n),
Err(e) => Err(e),
}
}
// As with `Option`, we can use combinators such as `map()`.
// This function is otherwise identical to the one above and reads:
// Modify n if the value is valid, otherwise pass on the error.
fn double_number_map(number_str: &str) -> Result<i32, ParseIntError> {
number_str.parse::<i32>().map(|n| 2 * n)
}
fn print(result: Result<i32, ParseIntError>) {
match result {
Ok(n) => println!("n is {}", n),
Err(e) => println!("Error: {}", e),
}
}
fn main() {
// This still presents a reasonable answer.
let twenty = double_number("10");
print(twenty);
// The following now provides a much more helpful error message.
let tt = double_number_map("t");
print(tt);
}