Result

Result is similar to Option, but with the added advantage of storing arbitrary error values with more context on the error, instead of just None. This type is suitable when we want the user to know why an operation failed. Here's the type signature of Result:

enum Result<T, E> {   Ok(T),    Err(E), } 

It has two variants, both of which are generic. Ok(T) is the variant we use for the success state putting in any value, T, while Err(E) is what we use in the error state putting in any error value, E. We can create them like so:

// create_result.rsfn main() {    let my_result = Ok(64);    let my_err = Err("oh no!");}

However, this does not compile, and we receive the following error message:

As Result has two generic variants and we gave the concrete ...

Get Mastering Rust - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.