知识卡片
数据转字段需标识符
配置文件的键是字符串,Rust 字段名需要标识符 token。在 quote! 内插入字符串会得到字符串字面量。本章用 proc_macro2::Ident 表达配置键对应的字段名,于是同一个标识符可以用于声明字段和构造实例。
书中专门区分了 proc_macro2::Ident 和编译器接口的 proc_macro::Ident。后者在示例中无法满足 quote! 插值所需的 ToTokens 约束。将外部字符串直接用作标识符还需要核实其语法有效性,教材清单中的 Ident::new 并未提供适用于各种 YAML 键的错误处理。
相关卡片 [[同库复用多个过程宏]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Macros and the outside world 同一 crate 的另一种宏入口 · 查看原书依据
By now, all of this is child’s play—except that I forgot for a moment that I had to turn the keys into identifiers, meaning I was greeted by an expected identifier error. Make sure to use Ident from proc_macro2 as well. If your IDE selects the one from proc_macro, you will be warned that the trait bound proc_macro::Ident: ToTokens is not satisfied. quote expects a ToTokens implementation to change your code into a TokenStream.