Coming from other functional languages (and being a Rust newbie), I'm a bit surprised by the motivation of Rust's if let
syntax. The RFC mentions that without if let
, the "idiomatic solution today for testing and unwrapping an Option<T>
" is either
match opt_val {
Some(x) => {
do_something_with(x);
}
None => {}
}
or
if opt_val.is_some() {
let x = opt_val.unwrap();
do_something_with(x);
}
In Scala, it would be possible to do exactly the same, but the idiomatic solution is rather to map
over an Option
(or to foreach
if it is only for the side effect of doing_something_with(x)
).
Why isn't it an idiomatic solution to do the same in Rust?
opt_val.map(|x| do_something_with(x));
.map()
is specific to the Option<T>
type, but if let
(and while let
!) are features that work with all Rust types.