为什么Rust需要`if let`语法? [英] Why does Rust need the `if let` syntax?

查看:515
本文介绍了为什么Rust需要`if let`语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自其他功能语言(并且是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);
}

在Scala中,可以做完全相同的事情,但是惯用的解决方案是在Option上使用map(或者,如果仅出于doing_something_with(x)的副作用,则使用foreach).

为什么在Rust中做同样的事情不是惯用的解决方案?

opt_val.map(|x| do_something_with(x));

解决方案

.map()特定于Option<T>类型,但是if let(和while let!)是适用于所有Rust类型的功能. /p>

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.

这篇关于为什么Rust需要`if let`语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆