How it works...

The try! macro enables us to simply unwrap without using panic. In the previous recipes, we used the unwrap and nested functionality many times to get the desired value. And try! is equivalent to an unwrap function that is returned instead of panic in the case of an error. In this recipe, you will learn how to use try! along with combinators.

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 type input and returns aResult<T> type. We declare a variable named first and assign it to try! macro statements for different cases. First, we check whether the first element of the vector is empty using vec.first(), which fetches the first value of the vector, if it's empty, we print a statement using the ok_or method and in the other try! we parse the first variable to an interger type. In case there is an error, we convert the error into a string using the map_err method.
  • print: This function takes in Result<T>. 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 only had string values. When we call the double_first function with these input values, 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
3.22.41.212