In Rust, you can use if let
instead of match
when it comes to unwrapping and directly using just a simple value.
So instead of
match opt_val {
Some(x) => {
do_something_with(x);
}
_ => {}
}
you can do
if let Some(x) = opt_val {
do_something_with(x);
}
How should I read or process this code mentally? For match
, this is straightforward: "If opt_val
is matched by Some(x)
then do... with x
".
For if let
I always have the impression that it is the wrong way round: "If Some(x)
matches(?) opt_val
, then do....". Note that there is no let
in this sentence.
It is no big deal, but I continue to stumble over this.
I really like "if this let binding succeeds then..." from the accepted answer, as I think it sets the right focus. Concentrating too much on the pattern matching got me into this "problem" in the first place.
For reference, (ir)refutability and let
is discussed here in the Rust book.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…