“上下文"和“上下文"有什么区别?和“with_context"无论如何? [英] What is the difference between "context" and "with_context" in anyhow?

查看:162
本文介绍了“上下文"和“上下文"有什么区别?和“with_context"无论如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于 anyhow Context 的文档:

This is the documentation for anyhow's Context:

/// Wrap the error value with additional context.
fn context<C>(self, context: C) -> Result<T, Error>
where
    C: Display + Send + Sync + 'static; 

/// 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;

在实践中,区别在于 with_context 需要一个闭包,如 anyhow 的 自述文件:

In practice, the difference is that with_context requires a closure, as shown in anyhow's README:

use anyhow::{Context, Result};

fn main() -> Result<()> {
    // ...
    it.detach().context("Failed to detach the important thing")?;

    let content = std::fs::read(path)
        .with_context(|| format!("Failed to read instrs from {}", path))?;
    // ...
}

但看起来我可以用context替换with_context方法,通过删除||来摆脱闭包,行为程序的内容不会改变.

But it looks like I can replace the with_context method with context, get rid of the closure by deleting ||, and the behaviour of the program wouldn't change.

这两种方法到底有什么区别?

What is the difference between the two methods under the hood?

推荐答案

提供给 with_context 的闭包是惰性求值的,这也是你使用 with_context 而不是 code>context 与您选择懒惰评估任何事情的原因相同:它很少发生并且计算成本很高.一旦满足这些条件,with_context 就比 context 更可取.注释伪示例:

The closure provided to with_context is evaluated lazily, and the reason you'd use with_context over context is the same reason you'd choose to lazily evaluate anything: it rarely happens and it's expensive to compute. Once those conditions are satisfied then with_context becomes preferable over context. Commented pseudo-example:

fn calculate_expensive_context() -> Result<()> {
    // really expensive
    std::thread::sleep(std::time::Duration::from_secs(1));
    todo!()
}

// eagerly evaluated expensive context
// this function ALWAYS takes 1+ seconds to execute
// consistently terrible performance
fn failable_operation_eager_context(some_struct: Struct) -> Result<()> {
    some_struct
        .some_failable_action()
        .context(calculate_expensive_context())
}

// lazily evaluated expensive context
// function returns instantly, only takes 1+ seconds on failure
// great performance for average case, only terrible performance on error cases
fn failable_operation_lazy_context(some_struct: Struct) -> Result<()> {
    some_struct
        .some_failable_action()
        .with_context(|| calculate_expensive_context())
}

这篇关于“上下文"和“上下文"有什么区别?和“with_context"无论如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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