← 返回起始笔记位置

知识卡片

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

从字段生成构建器代码

理解等级:中级

对于命名字段,构建器派生宏先从语法树提取字段名和类型。以书中的 roots_of: String 为例,派生展开为四类片段:构建器内的 roots_of: Option<String>、builder() 中的 None、接收 String 并写入 Some(input) 的 setter,以及在 build() 里填入原结构体的字段表达式。外层 Option 记录该字段是否设置。章中最早的实现用 expect 处理缺值,运行到缺值时会 panic。

插值应先把 f.ident 等访问结果绑定到局部变量,再交给 quote!。重复语法须按展开位置选分隔符。字段列表可以写 #(#builder_fields,)*,多个实现方法可写 #(#builder_methods)*。

相关卡片 [[派生宏生成构建器]]、[[消耗构建器以移动字段]]。

结构图:

classDiagram
    class Gleipnir {
        roots_of String
        +builder() GleipnirBuilder
    }
    class GleipnirBuilder {
        roots_of Option~String~
        +roots_of(&mut self, input String) &mut Self
        +build(&self) Gleipnir
    }
    Gleipnir ..> GleipnirBuilder : 创建初始构建器
    GleipnirBuilder ..> Gleipnir : 构造目标值
这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Testing a builder macro 从命名字段生成四类片段 · 查看原书依据

      Figure 6.3 shows an overview of the output generated by the different parts of our code and how everything fits together. From a simple struct with a single field, we generate a builder with a property, its initialization, a method to set its one field, and a build method where the original Gleipnir struct is created.

    参考来源

    - 位置:《Write Powerful Rust Macros》第06章《Testing a builder macro》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-6.xhtml#p86) - 结论依据:清单 6.11–6.16 及图 6.3 将每个 Field 的名字和类型分别映射为中间字段、初始值、setter 与目标字段表达式。 - 原始内容:Figure 6.3 shows an overview of the output generated by the different parts of our code and how everything fits together. From a simple struct with a single field, we generate a builder with a property, its initialization, a method to set its one field, and a build method where the original Gleipnir struct is created.