知识卡片

结构图卡 · 6074.c.2.b

状态载荷排除非法组合

理解等级:中级

带数据枚举把互斥状态与所需载荷绑定,而非让bool与另一个字段靠注释保持一致。单色分支不携带前景色,彩色分支才有RgbColor,因而不能构造那种字段错配。它排除的是类型已表达的不变量,不会自动验证颜色值、坐标范围或所有业务规则。

结构图:

classDiagram
class Color {
  <<enumeration>>
  Monochrome
  Foreground(RgbColor)
}
class DisplayProps {
  +u32 x
  +u32 y
  +Color color
}
class RgbColor
DisplayProps --> Color : color字段
Color --> RgbColor : Foreground载荷

Foreground是枚举变体的载荷形式,不是普通实例方法;箭头表示包含的类型关系,不推断所有权之外的额外生命周期。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第1章《enums with Fields》(spine5;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch01.html;u011-ch01-008)。 - 结论依据:原文在“make invalid states inexpressible”附近的定义、例子或代码支撑本卡核心说明:带数据枚举把互斥状态与所需载荷绑定,而非让bool与另一个字段靠注释保持一致。边界按已读前提解释;示例未执行。 - 原始内容:make invalid states inexpressible in your types. Types that support only valid combinations of values mean that whole classes of errors are rejected by the compiler, leading to smaller and safer code.