知识卡片

普通读书笔记卡 · 743.d

Option显式表达缺失

理解等级:中级

Option用Some(T)表达有值,用None表达缺失,让接口直接声明值可能不存在。它避免把-1、空指针或其他有效值充当隐含哨兵。选择Option后仍要决定缺失时怎样响应;类型表达了可能性,不会替调用者决定业务默认值。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 1. Types Option<T> · 查看原书依据

      either there’s a value of a particular type (Some(T)) or there isn’t (None). Always use Option for values that can be absent; never fall back to using sentinel values (-1, nullptr, …) to try to express the same concept in-band. There is one subtle point to consider, though. If you’re dealing with a collection of things, you need to decide whether having zero

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《Option<T>》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u013-ch01-009)。 - 结论依据:原文在“either there’s a value”附近的定义、例子或代码支撑本卡核心说明:Option<T>用Some(T)表达有值,用None表达缺失,让接口直接声明值可能不存在。边界按已读前提解释;示例未执行。 - 原始内容:either there’s a value of a particular type (Some(T)) or there isn’t (None). Always use Option for values that can be absent; never fall back to using sentinel values (-1, nullptr, …) to try to express the same concept in-band. There is one subtle point to consider, though. If you’re dealing with a collection of things, you need to decide whether having zero