知识卡片
生成名字需要标识符
quote! 按值的 ToTokens 实现写入 token。把 String 插入 fn #name(...) 会得到带引号的字符串字面量,编译器在函数名处却需要标识符。应先用 format!("get_{field_name}") 得到拼写,再用 Ident::new(..., span) 生成带跨度的标识符 token。字段访问 &self.#field_name 同样需要字段的 Ident,字段类型可直接插入 syn::Type。
逐字段得到方法片段后,#(#methods)* 将它们放进 impl,这里无需添加字段声明用的逗号。可把片段收集为 Vec<proc_macro2::TokenStream>,简化返回类型。
相关卡片 [[用跨度选择名称解析位置]]、[[用共享借用提供字段访问]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Hiding information and creating mini-DSLs with function-like macros 字段驱动的方法生成 · 查看原书依据
That’s the overview. Now focus on the code inside map. Besides the field name and type, we want to create a method name that consists of the field name prefixed with get (e.g., get_string_value).
参考来源
- 位置:《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#p38)
- 结论依据:第 5.1.3 节提供 expected identifier 的报错、Ident::new 的构造、图 5.2 的替换过程与清单 5.5 的 impl 输出。
- 原始内容:That’s the overview. Now focus on the code inside map. Besides the field name and type, we want to create a method name that consists of the field name prefixed with get (e.g., get_string_value).