知识卡片
忽略缺失时使用if let
只关心Some分支并且允许忽略None时,if let可清楚表达单分支处理。若缺失也需要行为、错误记录或业务决定,应显式保留那个分支。简化语法不能成为把未处理情况悄悄丢掉的理由。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 1. Types Item 3: Prefer Option and Result transforms over explicit match expressions · 查看原书依据
if let expression is one line shorter and, more importantly, clearer: if let Some(i) = &s.field { println!("field is {i}"); } However, most of the time the programmer needs to provide the corresponding else arm: the absence of a value (Option::None), possibly with an associated error (Result::Err(e)), is something that the programmer needs to deal with. Desi
参考来源
- 位置:《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-022)。
- 结论依据:原文在“if let”附近的定义、例子或代码支撑本卡核心说明:只关心Some分支并且允许忽略None时,if let可清楚表达单分支处理。边界按已读前提解释;示例未执行。
- 原始内容:if let expression is one line shorter and, more importantly, clearer: if let Some(i) = &s.field { println!("field is {i}"); } However, most of the time the programmer needs to provide the corresponding else arm: the absence of a value (Option::None), possibly with an associated error (Result::Err(e)), is something that the programmer needs to deal with. Desi