【发布时间】:2021-04-04 04:22:43
【问题描述】:
这是无论如何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 的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方法,通过删除||摆脱闭包,程序的行为不会改变。
这两种方法在底层有什么区别?
【问题讨论】:
-
如果你看一下源码,和docs.rs/anyhow/1.0.36/src/anyhow/context.rs.html#42-60一模一样
-
我明白了。那么在运行时有什么区别吗?我没有看到为相同的确切功能提供两个功能的好处。
-
不同之处在于,即使 Result 不是 Err,一个也会评估您可能非常复杂的上下文,而另一个仅在实际需要该上下文时调用创建上下文的闭包。这正是
with_content的文档提到的内容:使用附加上下文包装错误值,该上下文仅在发生错误时延迟评估。
标签: methods error-handling rust closures lazy-evaluation