In Rust we use the match expression to
check for errors in the
Result:
Generally speaking you want to perform different actions depending on
the error type:
Ditching match altogether
A more elegant way of writing the above:
Panic on Error shortcuts
unwrap
If the Result value is Ok,
unwrap
will return the value inside the Ok. If the Result is of the Err
variant, unwrap will call the panic! macro
expect
expect
is almost the same as unwrap, the only difference being that it allws us
to choose the panic! error message:
Propagating Errors
When you’re writing a function whose implementation calls something that
might fail, instead of handling the error within this function, you can
return the error to the calling code so that it can decide what to do.
This is known as propagating the error and gives more control to the
calling code, where there might be more information or logic that
dictates how the error should be handled than what you have available in
the context of your code.
This can of course be refactored to something nicer: