Unwrapping a Result
Many functions in Rust have their return values wrapped in a result
. The Result
type is an enum with two variants, Ok
and Err
.
It is common to have to handle these cases separately. One can use a match
statement, like so:
but this is in fact so common that there is a shortcut method called unwrap
:
Returning and the question mark
If we don't want to panic (and exit), we can return an error instead:
Just like calling .unwrap()
on a Result
is a shortcut for match
with panic!
in the error arm, ?
is a shortcut for a match
with a return
in the error arm:
Sources
Last updated