知识卡片

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

字符串属性生成标识符

理解等级:中级

用字符串属性指定方法名时,先解析成 syn::LitStr,再调用 value() 得到内容,使用 Ident::new(&literal.value(), literal.span()) 生成标识符。把原 token 整体转字符串会保留引号,让 Rust 把所得内容视为非法标识符。属性语法应要求名称符合生成标识符的位置。沿用参数跨度便于把诊断指到指定名字的地方。

相关卡片 [[字段名与生成方法名分离]]、[[用跨度指向宏输入错误]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Builder with attributes 理解属性形态与取值 · 查看原书依据

      Now all that is left is to transform this literal into an identifier we can use to construct the method name. For that we use the value helper method and the span of the existing literal, passing them to the new method. It may seem like retrieving the token, changing it into a string, and taking a reference (i.e., &nested_lit.token().to_ string()) would also work. Unfortunately, that code will error: "\"tops_of\\"" is not a valid identifier.

    参考来源

    - 位置:《Write Powerful Rust Macros》第08章《Builder with attributes》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-8.xhtml#p40) - 结论依据:8.1.2 对照 LitStr::value 取得的内部字符串和把字面量整段转字符串所得的带引号 token。 - 原始内容:Now all that is left is to transform this literal into an identifier we can use to construct the method name. For that we use the value helper method and the span of the existing literal, passing them to the new method. It may seem like retrieving the token, changing it into a string, and taking a reference (i.e., &nested_lit.token().to_ string()) would also work. Unfortunately, that code will error: "\"tops_of\\"" is not a valid identifier.