← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 6074.d.1.a.3.c.11.a.3.c · 生成模型:GPT-6

根属性启用字段默认值

理解等级:中级

构建器可以用结构体上的 #[builder_defaults] 控制缺值策略。生成器查找根属性后,为每个中间 Option<T> 生成 unwrap_or_default()。已有 Some(value) 时仍取该值,遗漏时才使用 T::default()。示例在未启用开关时继续生成 expect,在启用时则要求各字段类型都支持 Default,即使某次调用设齐字段也是如此。类型默认值未必是业务上的正确缺省项,是否启用应当由 API 配置表达。

相关卡片 [[派生辅助属性配置展开]]、[[用跨度标注特征约束]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Builder with attributes 默认值配置与生成闭包 · 查看原书依据

      As you can see, attributes are present both at the root level of DeriveInput and at the field level. Previously, we were adding attributes to individual fields. This time we placed one on top of our struct. So we should look in the root. Our use_defaults helper is simple. It checks whether any attribute identifier matches the name builder_defaults. The result is given to original_struct_setters, the only method that needs to know about it.

    参考来源

    - 位置:《Write Powerful Rust Macros》第08章《Builder with attributes》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-8.xhtml#p71) - 结论依据:清单 8.11–8.14 从 DeriveInput.attrs 提取开关,再改变每个字段初始化的生成片段。 - 原始内容:As you can see, attributes are present both at the root level of DeriveInput and at the field level. Previously, we were adding attributes to individual fields. This time we placed one on top of our struct. So we should look in the root. Our use_defaults helper is simple. It checks whether any attribute identifier matches the name builder_defaults. The result is given to original_struct_setters, the only method that needs to know about it.