Calling functions that return Result

When we call a function that returns Result, the return value is—as requested—a Result, rather than the data type we really need. There are several ways of working with that, depending on our specific needs.

The simplest way to deal with a Result is to use the ? operator, which extracts the stored value from a successful Result, or returns a Result containing the error value if the Result it's looking at indicates an error. Because ? might return from the current function in the same way that a return statement would, ? can only be used in functions that themselves return Result and use the same data type to represent errors. Using ? looks like this:

let mut cons: Constrained = new_constrained(0, 10, 5)?; 

Here, we're calling the new_constrained function, which returns either a successful result or an error message. However, the variable we're assigning to has Constrained as its type, not Result. That works because of the ? at the end, which pulls out the Constrained value if the function call succeeds, and returns if the function call fails.

The next easiest way to deal with a returned Result is to use the expect function. This function does something similar to the ?, pulling out the success value if Result indicates success, but it handles failure differently. Instead of returning an error from the current function, expect terminates the whole program and prints out an error message. Functions that use expect don't have to return a Result, so it can be used in some situations where ? is unavailable. Using expect looks like this:

let mut cons: Constrained = new_constrained(0, 10, 5).expect("Something went very wrong");

The parameter passed to expect is the error message it should display on failure. There are some other functions, similar to expect, that handle errors in various ways, such as calling an error handler function.

Finally, we can actually handle the errors ourselves, by checking whether the returned Result is an Ok or an Err. That is done by using the match or if let expressions, which we will learn about in Chapter 4the Making Decisions by Pattern Matching.

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

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