知识卡片

普通读书笔记卡 · 743.d.4

取值失败的崩溃策略

理解等级:中级

unwrap和expect在Option为None或Result为Err时触发panic,expect只是增加说明消息。它们适合调用者已证明不变量或明确接受终止的场合,不会把可失败操作变成安全操作。库通常应保留错误交给调用者,而不是替应用决定崩溃策略。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Item 3: Prefer Option and Result transforms over explicit match expressions》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u022-ch01-023)。 - 结论依据:原文在“unwrap”附近的定义、例子或代码支撑本卡核心说明:unwrap和expect在Option为None或Result为Err时触发panic,expect只是增加说明消息。边界按已读前提解释;示例未执行。 - 原始内容:unwrap and expect. The latter allows the error message on failure to be personalized, but in either case, the resulting code is shorter and simpler—error handling is delegated to the .unwrap() suffix (but is still present): let f = std::fs::File::open("/etc/passwd").unwrap(); Be clear, though: these helper functions still panic!, so choosing to use them is t