Follow these steps to get through this recipe:
- Create a file named sample_map_result.rs and open it in your text editor.
- Write the code header with the relevant information:
//-- #########################
//-- Task: Implementing map for Result
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 26 March 17
//-- #########################
- Call the standard library:
use std::num::ParseIntError;
- Create a function named double_number that will accept the str input and return a Result<T> type:
fn double_number(number_str: &str) -> Result<i32,
ParseIntError> {
match number_str.parse::<i32>() {
Ok(n) => Ok(2 * n),
Err(e) => Err(e),
}
}
- Create a function named double_number_map that will accept the str input and return a Result<T> type:
fn double_number_map(number_str: &str) -> Result<i32,
ParseIntError> {
number_str.parse::<i32>().map(|n| 2 * n)
}
- Create a function named print that will accept a Result<T> type as input:
fn print(result: Result<i32, ParseIntError>) {
match result {
Ok(n) => println!("n is {}", n),
Err(e) => println!("Error: {}", e),
}
}
- Define the main function and declare different input for different functions:
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);
}
You will get the following output upon successful execution of the code: