try!() macro for the Option type in Rust
In Rust you can't use the try!() macro with Option types:
let last = try!(vec![1,2,3].last());
error: mismatched types:
expectedcore::option::Option<&_>,
foundcore::result::Result<_, _>
but you can easily convert Option to Result to make it work:
struct MyErrorType;
let last = try!(vec![1,2,3].last().ok_or(MyErrorType)); // strings are convertible to errors, so you can use them too.
Just add ok_or() to the expression and give it an instance of an error that should be used instead of None.
It also works with ? operator.
Written by Kornel
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rust
Authors
pornel
137.5K
bobwilliams
1.991K
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#