Last Updated: February 10, 2017
· pornel

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:
expected core::option::Option<&_>,
found core::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.