← 返回起始笔记位置

知识卡片

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

数据转字段需标识符

理解等级:中级

配置文件的键是字符串,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.

    参考来源

    - 位置:《Write Powerful Rust Macros》第10章《Macros and the outside world》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-10.xhtml#p56) - 结论依据:原文先复盘字符串键导致期望标识符的错误,再解释选错 Ident 类型会因 ToTokens 实现不匹配而失败。 - 原始内容: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.