我来自其他函数式语言(也是一个Rust新手),我对Rust的if let
语法的动机有点惊讶.RFC提到,如果没有if let
,"今天用于测试和展开Option<T>
的惯用解决方案"是
match opt_val {
Some(x) => {
do_something_with(x);
}
None => {}
}
或
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
(或 to f或each
if it is only f或 the side effect of doing_something_with(x)
).
为什么这不是一个惯用的解决方案,在Rust 时也这么做?
opt_val.map(|x| do_something_with(x));