1 个稳定版本

1.0.0 2023年3月6日

#29 in #expect

MIT/Apache

4KB

expect_with

Crates.io Documentation

expect_with() 添加了 Option<T>Result<T, E>,其中 EDebug(所有具有 expect 方法的 std 类型)。

此方法与 except() 功能完全相同,但仅在实际发生错误时评估错误信息。

示例

fn some_heavy_function() -> String {
    return String::from("42");
}

let result: Result<(), String> = Err(String::from("some error"));
result.expect_with(|| format!("error {}", some_heavy_function()));

动机

使用 expect 有一个主要的缺点。它每次都会计算它的参数。即使没有发生错误。如果 expect 被频繁调用,并且评估错误信息涉及一些计算(即使是简单的 format 也可能非常慢),这可能会非常慢。expect_with 通过接受 lambda 来消除这种开销,它只在实际需要时才会执行以获取错误信息。

无运行时依赖