map()
is intended for transforming an optional value, while if let
is mostly needed to perform side effects. While Rust is not a pure language, so any of its code blocks can contain side effects, map semantics is still there. Using map()
to perform side effects, while certainly possible, will only confuse readers of your code. Note that it should not have performance penalties, at least in simple code - LLVM optimizer is perfectly capable of inlining the closure directly into the calling function, so it turns to be equivalent to a match
statement.
Before if let
the only way to perform side effects on an Option
was either a match or if
with Option::is_some()
check. match
approach is the safest one, but it is very verbose, especially when a lot of nested checks are needed:
match o1 {
Some(v1) => match v1.f {
Some(v2) => match some_function(v2) {
Some(r) => ...
None => {}
}
None => {}
}
None => {}
}
Note the prominent rightward drift and a lot of syntactical noise. And it only gets worse if branches are not simple matches but proper blocks with multiple statements.
if option.is_some()
approach, on the other hand, is slightly less verbose but still reads very badly. Also its condition check and unwrap()
are not statically tied, so it is possible to get it wrong without the compiler noticing it.
if let
solves the verbosity problem, based on the same pattern matching infrastructure as match
(so it is harder to get wrong than if option.is_some()
) and, as a side benefit, allows using arbitrary types in patterns, not only Option
. For example, some types may not provide map()
-like methods; if let
will still work with them very nicely. So if let
is a clear win, hence it is idiomatic.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…