知识卡片
按可恢复性选择失败方式
Result 适用于会在正常运行中发生且调用方有权决定如何处理的失败。panic 可用于不变量失效而后续执行不安全的情况,应公开记录触发条件。测试中的辅助操作失败可以用 panic 标记失败;已在程序内部确定的假设可用 expect 记录依据。
相关卡片 [[错误传播保留调用者决定]]、[[恐慌消息记录成功假设]]
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 错误处理 To panic! or Not to panic! · 查看原书依据
If someone calls your code and passes in values that don’t make sense, it’s best to return an error if you can so the user of the library can decide what they want to do in that case. However, in cases where continuing could be insecure or harmful, the best choice might be to call panic!
参考来源
- 位置:《The Rust Programming Language(第2版)》第09章 错误处理(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c09.xhtml`,块 0151)
- 结论依据:原文让库尽量把错误交给调用者,同时说明继续运行有害时的边界。
- 原始内容:If someone calls your code and passes in values that don’t make sense, it’s best to return an error if you can so the user of the library can decide what they want to do in that case. However, in cases where continuing could be insecure or harmful, the best choice might be to call panic!