相关疑难解决方法(0)

为什么Rust需要`if let`语法?

来自其他函数式语言(并且是Rust新手),我对Rust if let语法的动机感到有些惊讶.该RFC提到,如果没有if let,则"测试惯用的解决方案今天展开的Option<T>"或者是

match opt_val {
    Some(x) => {
        do_something_with(x);
    }
    None => {}
}
Run Code Online (Sandbox Code Playgroud)

要么

if opt_val.is_some() {
    let x = opt_val.unwrap();
    do_something_with(x);
}
Run Code Online (Sandbox Code Playgroud)

在Scala中,可以完全相同,但惯用的解决方案是map覆盖Option(或者foreach仅仅是为了副作用doing_something_with(x)).

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

opt_val.map(|x| do_something_with(x));
Run Code Online (Sandbox Code Playgroud)

option rust

12
推荐指数
2
解决办法
4039
查看次数

无论如何,“context”和“with_context”之间有什么区别?

这是无论如何Context的文档:

/// Wrap the error value with additional context.
fn context<C>(self, context: C) -> Result<T, Error>
where
    C: Display + Send + Sync + 'static; 
Run Code Online (Sandbox Code Playgroud)
/// Wrap the error value with additional context that is evaluated lazily
/// only once an error does occur.
fn with_context<C, F>(self, f: F) -> Result<T, Error>
where
    C: Display + Send + Sync + 'static,
    F: FnOnce() -> C;
Run Code Online (Sandbox Code Playgroud)

在实践中,不同之处在于with_context需要一个闭包,如无论如何的README所示:

use anyhow::{Context, Result};

fn main() -> Result<()> { …
Run Code Online (Sandbox Code Playgroud)

methods error-handling closures lazy-evaluation rust

3
推荐指数
2
解决办法
498
查看次数