Rust Notes #1: If Let, Question Mark Operator
On my quest to learn Rust, I'm reading The Rust Programming Language. The book reveals some interesting language features that lead to more concise code.
If Let
Rust has powerful pattern matching constructs, like match
. Sometimes, though, match
leads to unnecessary verbosity.
In some cases, using if let
instead of match
leads to greater concision. For example, you could replace:
let an_option = Some(4);
match an_option {
Some(num) => {
println!("{}", num);
}
_ => {}
}
With this variation:
let an_option = Some(4);
if let Some(num) = an_option {
println!("{}", num);
}
The if let
variant destructures the value in an_option
in a concise way. Rust by Example has more examples, including how to handle error cases.
Question Mark Operator
Without some magic, handling Result
and Option
types means boilerplate match
expressions. The question mark operator ?
reduces that boilerplate by either evaluating to the unwrapped value inside OK
or immediately returning and propagating the Err
.
Here's an imaginary example:
fn get_some_data() -> Result<i32, SomeErrorType> {
some_unreliable_service::get_data()?
}
Instead of writing code that handles and manually returns the potential error from the call to get_data
, the question mark operator will automatically return and propagate the Error case.
For more examples, see the book's section on the question mark operator.