知识卡片
缺失与失败使用不同结果
合法不存在的值可用Option,需说明失败原因的操作可用Result。空集合的first没有元素可以是正常缺失;解析失败则常需保留错误类型。将Result改成Option会丢掉错误信息,只有调用者明确不需要原因时才合适。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Item 3: Prefer Option and Result transforms over explicit match expressions · 查看原书依据
first situation where a match is unnecessary is when only the value is relevant and the absence of value (and any associated error) can just be ignored: struct S { field: Option<i32>, } let s = S { field: Some(42) }; match &s.field { Some(i) => println!("field is {i}"), None => {} } For this situation, an if let expression is one line shorter and, more impor
参考来源
- 位置:《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-024)。
- 结论依据:原文在“first”附近的定义、例子或代码支撑本卡核心说明:合法不存在的值可用Option,需说明失败原因的操作可用Result。边界按已读前提解释;示例未执行。
- 原始内容:first situation where a match is unnecessary is when only the value is relevant and the absence of value (and any associated error) can just be ignored: struct S { field: Option<i32>, } let s = S { field: Some(42) }; match &s.field { Some(i) => println!("field is {i}"), None => {} } For this situation, an if let expression is one line shorter and, more impor