← 返回刚才阅读的位置

知识卡片

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

重写须保留其余语法

理解等级:高级

属性宏重新发射项目时,输出模板决定哪些原语法能留下。只抽取结构体名称、字段名和字段类型会漏掉类型参数和约束,以及结构体和字段上原有的属性。书中把 #[derive(Debug)] 放在 #[public] 下方即可观察到它在展开中消失。保留传入的属性才能维护其他宏组合的行为,位置调整只能解释该例为何变化。对于只修改可见性的需求,可优先考虑在现有 AST 上改可见性后重新输出。

如果选择针对不同类型重建,需区分 struct Named {}、struct Tuple(u32, String); 和 struct Unit;。命名字段模板能处理空花括号,元组形态需保留括号及分号,单元形态需单独覆盖。枚举公开时,变体随枚举具有可见性,不给变体字段添加 pub。输入里只有另一结构体的类型名时,宏没有获得该类型定义,要公开其字段需对定义另做处理。

相关卡片 [[属性宏替换原项目]]、[[从语法树提取命名字段]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Making fields public with attribute macros 重建时遇到的信息损失 · 查看原书依据

      A much bigger problem is that when we have other macros annotating our struct, they are deleted by ours. Try adding a #[derive(Debug)] below our annotation and running cargo expand. Do you see how the additional annotation vanishes into thin air? We are simply superb at making things disappear. As macros are executed in order, from top to bottom, the simple workaround is adding the derive above our #[public]. Now everything will work as

    参考来源

    - 位置:《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#p73) - 结论依据:第 4.5 节用 derive 消失、泛型签名丢失、元组和单元形态说明手工模板保留边界。空元组是否匹配由清单 4.9 的 Named 分支决定。 - 原始内容:A much bigger problem is that when we have other macros annotating our struct, they are deleted by ours. Try adding a #[derive(Debug)] below our annotation and running cargo expand. Do you see how the additional annotation vanishes into thin air? We are simply superb at making things disappear. As macros are executed in order, from top to bottom, the simple workaround is adding the derive above our #[public]. Now everything will work as