← 返回起始笔记位置

知识卡片

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

属性宏替换原项目

理解等级:初级

在标记为过程宏库的 crate 根定义 #[proc_macro_attribute] 公共函数,函数名就是属性名。写 #[public] 会触发 public。签名中的第一个 TokenStream 是当前属性名后括号里的参数,裸写 #[public] 时为空。第二个流是被标注的项目及传入的其他属性。项目可以是结构体、枚举,也可以是函数、特征等允许附加属性宏的项目。

属性宏的输出会接替原项目。书中用 #[public] struct Example {} 演示,若宏返回空流,展开结果便找不到这个结构体。派生宏生成的实现会追加到原类型之后,原类型仍在。需要把数据传输对象(DTO)的字段统一改为公开时,可以利用属性宏的替换语义。可见性是有意修改的部分,其他语法也需要随结果输出。

相关卡片 [[重写须保留其余语法]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Making fields public with attribute macros 字段可见性的改写动机 · 查看原书依据

      Attribute macros get their name from the fact that they define a new attribute. When you annotate a struct or enum with that new custom attribute, the macro will be triggered. Otherwise, writing the library and code for an attribute macro is quite similar to creating a derive macro. But there are differences as well: an attribute macro also receives a TokenStream containing additional attributes (if any). And—more importantly for

    参考来源

    - 位置:《Write Powerful Rust Macros》第04章《Making fields public with attribute macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-4.xhtml#p12) - 结论依据:清单 4.3 和图 4.1 显示双 TokenStream 签名,清单 4.4–4.5 对照空输出前后的项目。Rust Reference 对参数流与项目上其他属性的归属有明确说明。 - 原始内容:Attribute macros get their name from the fact that they define a new attribute. When you annotate a struct or enum with that new custom attribute, the macro will be triggered. Otherwise, writing the library and code for an attribute macro is quite similar to creating a derive macro. But there are differences as well: an attribute macro also receives a TokenStream containing additional attributes (if any). And—more importantly for