知识卡片
扩展时重发原结构体
private!(struct Example { ... }) 把结构体声明放在宏调用内部,生成 impl 时也需要将原声明重新输出。早期模板只从 AST 取名,新输出的空结构体丢失所有字段。保留原声明可在 parse_macro_input! 获取所有权前复制原 proc_macro::TokenStream,把副本转为实现 ToTokens 的 proc_macro2::TokenStream,再插值到输出。也可直接输出实现 ToTokens 的 DeriveInput,同时用 &ast.ident 取得名称,保留整体供插值。书中内部模块路径用于示范,公开类型路径更适合做依赖。
若输出的是与字段无关的固定方法,调用可只接受已在外部声明的类型名,再发出一个 impl。若要为每个字段生成返回类型各异的访问器,入口需要能够取得字段定义。
相关卡片 [[借用字段避免部分移动]]、[[用共享借用提供字段访问]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Hiding information and creating mini-DSLs with function-like macros 将结构体送回展开结果 · 查看原书依据
In the code in listing 5.3, we choose the first approach. Because the incoming stream is moved by parse_macro_input, we clone the stream and use the Into trait to change the built-in TokenStream into a type that implements the ToTokens trait required by the quote macro.
参考来源
- 位置:《Write Powerful Rust Macros》第05章《Hiding information and creating mini-DSLs with function-like macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-5.xhtml#p26)
- 结论依据:第 5.1.2 节对照副本与 AST 两种恢复原声明的路径,第 5.1.3 节和练习 1 展示按生成逻辑需要决定输入粒度。
- 原始内容:In the code in listing 5.3, we choose the first approach. Because the incoming stream is moved by parse_macro_input, we clone the stream and use the Into trait to change the built-in TokenStream into a type that implements the ToTokens trait required by the quote macro.