知识卡片
问号传播并转换错误
?在成功时取出值,在失败时提前返回当前函数;返回错误类型兼容时可通过From转换。它是传播而非忽略错误。若需要特别映射,可先map_err再用?;错误发生在哪一层以及是否补充上下文,仍需接口设计决定。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Item 3: Prefer Option and Result transforms over explicit match expressions · 查看原书依据
map_err() transformation: pub fn find_user(username: &str) -> Result<UserId, String> { let f = std::fs::File::open("/etc/passwd") .map_err(|e| format!("Failed to open password file: {:?}", e))?; // ... } Better still, even this may not be necessary—if the outer error type can be created from the inner error type via an implementation of the From standard tra
参考来源
- 位置:《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-025)。
- 结论依据:原文在“map_err”附近的定义、例子或代码支撑本卡核心说明:?在成功时取出值,在失败时提前返回当前函数;返回错误类型兼容时可通过From转换。边界按已读前提解释;示例未执行。
- 原始内容:map_err() transformation: pub fn find_user(username: &str) -> Result<UserId, String> { let f = std::fs::File::open("/etc/passwd") .map_err(|e| format!("Failed to open password file: {:?}", e))?; // ... } Better still, even this may not be necessary—if the outer error type can be created from the inner error type via an implementation of the From standard tra