知识卡片
标识符转文本再打印
宏输入中的名字可以用于输出类型位置,也可以插到诊断或输出文本里。用 quote! 插入 #name 会得到标识符 token。在生成的 impl #name 中,它是类型名。要在生成的 println! 中用它当文本,可以先在宏内调用 to_string() 再插入字符串,或生成 stringify!(#name) 让展开后的代码把它变成字面文本。
相关卡片 [[数据转字段需标识符]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Exercise solutions 第 3 章练习:派生输出与名字 · 查看原书依据
4. See if you can output a greeting followed by the name of the input (e.g., “Hello, Example”). Fair warning: passing #name to print will not be enough because that’s an identifier, and you need a string.
参考来源
- 位置:《Write Powerful Rust Macros》附录 A《Exercise solutions》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/appendix-a.xhtml#p35)
- 结论依据:练习明确说明插入 #name 会产生标识符,并给出宏内转字符串及在输出中使用 stringify! 两个选择。
- 原始内容:4. See if you can output a greeting followed by the name of the input (e.g., “Hello, Example”). Fair warning: passing #name to print will not be enough because that’s an identifier, and you need a string.