更新时间:2023-11-17 19:40:16
提供给 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())
}