How to do it...

Follow these steps to get through this recipe:

  1. Create a file named sample_error.rs and open it in your text editor.
  2. Write the code header with the relevant information:
        //-- #########################
//-- Task: Defining your own error type
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 26 March 17
//-- #########################
  1. Call the standard crates and create a generic alias type Result<T> for the std::result::Result<T, CustomError> type:
        use std::num::ParseIntError;
use std::fmt;

type Result<T> = std::result::Result<T, CustomError>;
  1. Create an enum type CustomError, which is our user-defined error type:
        #[derive(Debug)]
enum CustomError {
EmptyVec,
Parse(ParseIntError),
}
  1. Implement a customized way to display the error of the CustomError type:
        impl fmt::Display for CustomError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CustomError::EmptyVec =>
write!(f, "please use a vector with at least one
element"),
// This is a wrapper, so defer to the underlying
types' implementation of `fmt`.
CustomError::Parse(ref e) => e.fmt(f),
}
}
}
  1. Create a function named double_first that will accept the Vec input and return a Result<i32> type:
        fn double_val(vec: Vec<&str>) -> Result<i32> {
vec.first()
// Change the error to our new type.
.ok_or(CustomError::EmptyVec)
.and_then(|s| s.parse::<i32>()
// Update to the new error type here also.
.map_err(CustomError::Parse)
.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 numbers = vec!["93", "18"];
let empty = vec![];
let strings = vec!["tofu", "93", "18"];

print(double_val(numbers));
print(double_val(empty));
print(double_val(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.129.210.91