How it works...

In the previous recipe, we explicitly handled errors using combinators. Rust also provides us with another way to deal with these cases, where we use a combination of match statements and early returns. The early returns is a way by which we can catch errors at an early stage of the function process and return back to the user of the application or library.

First, we created an alias for std::result::Result<T, String> using the type keyword as Result<T>, which we will use across the functional units of the code.

Let's check out the working of all the functional units:

  • double_first: This function takes in the vec input and returns Result<T>. In our case, we used the early return Err to handle errors. We declared a variable named first, which held onto the first value of the vector that was passed. On this first variable, we performed match statements. If the value you get is None, use return Err to implement an early return to pass the error. In case you have string values in the vector element, use the Err value of the aliased type to raise the error.
  • print: This function takes in Result<T>, and using the match statement, we check whether we have an Ok or Err case for printing the corresponding statement.

In the main function, we had vectors in which one was empty, where there were no values in the vector. The other was string, where we had only string values when we called the double_first function. With this input, we get the corresponding errors.

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

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