知识卡片

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

字段属性触发类型校验

理解等级:中级

派生宏可声明自己接受的字段辅助属性,再根据属性内容决定生成什么代码。例如统一使用 #[builder(rename = "...")],入口先声明 attributes(builder),随后用 parse_nested_meta 查找内部键并抽取字符串。命名空间能明确选项属于哪一个宏。

字段属性也有适用类型。附录的 #[uppercase] 对带该属性的 String 字段生成 .map(|v| v.to_uppercase()),对其他字段类型给出定位字段名的 syn::Error,无该属性时插入空 token。针对每个字段产生的 Result 可以直接 collect 为整个集合的 Result,任一字段错误会阻止生成。

相关卡片 [[按调用控制代码生成]]、[[数据转字段需标识符]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Exercise solutions 第 8 章练习:辅助属性扩展 · 查看原书依据

      If this attribute is present and the field is a String (we use a helper from a previous chapter to verify this), we do a to_uppercase on our optional value. If we have the attribute but the type is not a string, we return a syn::Error. In all other cases, there’s nothing to do, so we return an empty stream.

    参考来源

    - 位置:《Write Powerful Rust Macros》附录 A《Exercise solutions》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/appendix-a.xhtml#p136) - 结论依据:这里的清单按属性存在与字段类型两项条件选择输出,并用 Result 收集传播生成错误。相邻 rename 解答给出了辅助属性的命名空间方案。 - 原始内容:If this attribute is present and the field is a String (we use a helper from a previous chapter to verify this), we do a to_uppercase on our optional value. If we have the attribute but the type is not a string, we return a syn::Error. In all other cases, there’s nothing to do, so we return an empty stream.