Follow these steps to get through this recipe:
- Create a file named sample_multiple_err.rs and open it in your text editor.
- Write the code header with the relevant information:
//-- #########################
//-- Task: Handling multiple errors
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 26 March 17
//-- #########################
- Define a generic alias named Result<T> for the std::result::Result<T, String> type:
type Result<T> = std::result::Result<T, String>;
- 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))
}
- 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),
}
}
- 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: