知识卡片

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

忽略缺失时使用if let

理解等级:中级

只关心Some分支并且允许忽略None时,if let可清楚表达单分支处理。若缺失也需要行为、错误记录或业务决定,应显式保留那个分支。简化语法不能成为把未处理情况悄悄丢掉的理由。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 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-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