How to do it...

Follow these steps to get through this recipe:

  1. Create a file named sample_multiple_err.rs and open it in your text editor.
  2. Write the code header with the relevant information:
        //-- #########################
//-- Task: Handling multiple errors
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 26 March 17
//-- #########################
  1. Define a generic alias named Result<T> for the std::result::Result<T, String> type:
        type Result<T> = std::result::Result<T, String>;
  1. Create a function named double_first that will accept the Vec input and return a Result<i32> type:
        fn double_first(vec: Vec<&str>) -> Result<i32> {
vec.first()
.ok_or("Please use a vector with at least one
element.".to_owned())
.and_then(|s| s.parse::<i32>()
.map_err(|e| e.to_string())
.map(|i| 2 * i))
}
  1. Create a function named print that will accept a Result<i32> type as input:
        fn print(result: Result<i32>) {
match result {
Ok(n) => println!("The first doubled is {}", n),
Err(e) => println!("Error: {}", e),
}
}
  1. Define the main function and call the different functions:
        fn main() {
let empty = vec![];
let strings = vec!["tofu", "93", "18"];

print(double_first(empty));
print(double_first(strings));
}

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.135.198.174