知识卡片

结构图卡 · 6074.d.1.a.3.c.11.a.5 · 生成模型:GPT-6

构建器用类型强制填字段

理解等级:高级

普通构建器允许暂缺字段时调用 build,因而要返回错误、填默认值或 panic。类型状态构建器把“接下来要填哪个字段”放进泛型。初始类型只提供第一个 setter,setter 消耗当前实例、保存值并返回下一阶段,只有 Builder<FinalBuilder> 对应的实现块提供 build。漏掉必填字段时,调用者连 build 方法都拿不到。

书中这一实现以声明顺序提供 setter,简化状态数量,但改变了可以任意顺序赋值的体验。想支持可选字段,需要另外设计其出现的阶段。示例仍在内部用 Option 传递已设置的值,外部调用合法性来自生成方法的可达关系。

相关卡片 [[类型状态限制可用操作]]、[[消耗构建器以移动字段]]、[[逆序生成类型状态转移]]。

结构图:

stateDiagram-v2
    [*] --> Roots : builder
    state "等待 roots_of" as Roots
    state "等待 breath_of_a_fish" as Breath
    state "等待 anything_else" as More
    state "FinalBuilder" as Complete
    Roots --> Breath : roots_of
    Breath --> More : breath_of_a_fish
    More --> Complete : anything_else
    Complete --> [*] : build
这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Builder with attributes 通过类型排除非法转移 · 查看原书依据

      What may be bothering you is how we seem to have only three choices to deal with missing properties: defaults, panics, and a Result return type. We have implemented the first two, and the latter option sounds nice and idiomatic. But it is not a perfect fit because there is no reason to allow mistakes in building our example structs. You either have all their required properties or you don’t. In the former case, the operation is always a success.

    参考来源

    - 位置:《Write Powerful Rust Macros》第08章《Builder with attributes》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-8.xhtml#p105) - 结论依据:图 8.6 和清单 8.21–8.31 在原有可空字段存储外增加泛型阶段,并通过缺失第三字段的编译诊断验证 build 受限。 - 原始内容:What may be bothering you is how we seem to have only three choices to deal with missing properties: defaults, panics, and a Result return type. We have implemented the first two, and the latter option sounds nice and idiomatic. But it is not a perfect fit because there is no reason to allow mistakes in building our example structs. You either have all their required properties or you don’t. In the former case, the operation is always a success.