How to do it...

Follow these steps to get through this recipe:

  1. Create a file named sample_map_result.rs and open it in your text editor.
  2. Write the code header with the relevant information:
        //-- #########################
//-- Task: Implementing map for Result
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 26 March 17
//-- #########################
  1. Call the standard library:
      use std::num::ParseIntError;
  1. 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),
}
}
  1. 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)
}
  1. 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),
}
}
  1. 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:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.235.188