我来自其他函数式语言(也是一个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));

推荐答案

.map()是针对Option<T>型的,但if let(和while let!)是适用于所有 rust 蚀类型的功能.

Rust相关问答推荐

Rust,polars CSV:有没有一种方法可以从impll BufRead(或任何字节迭代器)中读取CSV?

基于对vec值的引用从该值中删除该值

什么是Rust惯用的方式来使特征向量具有单个向量项的别名?

rust 蚀生命周期 行为

如何使用 list 在Rust for Windows中编译?

MPSC频道在接收器处阻塞

有没有一种惯用的方法来判断VEC中是否存在变体?

如何高效地将 struct 向量中的字段收集到单独的数组中

为什么 js_sys Promise::new 需要 FnMut?

根据掩码将 simd 通道设置为 0 的惯用方法?

如何在Rust中使用Serde创建一个自定义的反序列化器来处理带有内部标记的枚举

在 Bevy 项目中为 TextureAtlas 精灵实施 NearestNeighbor 的正确方法是什么?

Rust 函数指针似乎被borrow 判断器视为有状态的

当 T 不是副本时,为什么取消引用 Box 不会抱怨移出共享引用?

在 Rust 中返回对枚举变体的引用是个好主意吗?

当 `T` 没有实现 `Debug` 时替代 `unwrap()`

当用作函数参数时,不强制执行与绑定的关联类型

为什么这个值在上次使用后没有下降?

为什么 u64::trailing_zeros() 在无分支工作时生成分支程序集?

如何在宏中的多个参数上编写嵌套循环?