知识卡片
解析与插值生成实现
将派生输入解析为 syn::DeriveInput,取得类型的 ident 后,用 quote! { impl #name { /* 方法 */ } } 将名字令牌嵌入模板。这个宏返回的流转换为编译器要求的 proc_macro::TokenStream 后交给编译器。固定输出会绑定到硬编码类型,从输入取名可复用于不同类型。完整支持泛型还需要为 impl 传递参数与 where 子句。
相关卡片 [[令牌流与语法树的分工]]、[[名字符号与字符串]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
- · 按输入生成实现
原书出处 · 1 处
- A “Hello, World” procedural macro 按输入生成实现 · 查看原书依据
Once we have the DeriveInput, we can get the name of the struct by retrieving the topmost ident(ifier), which we save in a variable called name. If we want to use name in our output, we need a special syntax to tell quote that this is not a literal value but should be replaced with the content of a variable with a matching name.
参考来源
- 位置:《Write Powerful Rust Macros》第03章《A “Hello, World” procedural macro》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-3.xhtml#p60)
- 结论依据:原文从硬编码到 .ident 和 #name,展示同一方法模板如何跟随输入类型名。
- 原始内容:Once we have the DeriveInput, we can get the name of the struct by retrieving the topmost ident(ifier), which we save in a variable called name. If we want to use name in our output, we need a special syntax to tell quote that this is not a literal value but should be replaced with the content of a variable with a matching name.