There seem to be two obvious ways to handle a Result<T, E>
type.
The first is using match, which I believe is used in references such as the Rust Book most frequently.
match some_result {
Ok(value) => {
},
Err(error) => {
},
}
However, it is fairly trivial to accomplish the same thing using a combination of if
is_ok()
and unwrap()
.
if some_result.is_ok() {
let some_value = some_result.unwrap();
}
else {
}
The match is slightly more elegant in that it doesn't require an additional assignment statement, you already have the type from the name passed to Ok
.
There is a partner to unwrap()
, unwrap_err()
which returns the error, and panics if the result is an Ok
rather than an Err
.
This means it is possible to do something like:
if some_result.is_ok() {
let some_value = some_result.unwrap();
}
else {
let error = some_result.unwrap_err(); // panic if `Ok`
}
However, sometimes the if
statement is easier to use as match
requires that all branches be compatible in the type they return. (Trivial if ()
is the return type.)
It seems that the most appropriate choice is context dependent.
Is my understanding of the above points raised correct, or have I misunderstood something which means match
should be used instead of if
?