知识卡片
函数式宏替换调用
在过程宏 crate 的根使用 #[proc_macro] 标记公共函数 fn name(input: TokenStream) -> TokenStream,其函数名也是宏名。用 name!(...)、name![...] 或 name!{...} 调用时,函数接收外层定界符内的一条 token 流。它和 macro_rules! 的调用外形相同,可以出现在允许宏调用的项目、表达式等位置。
返回 token 替换整次调用,须满足调用位置的语法。例如 private! 在项目位置发出结构体和 impl,compose! 在等号后产生块表达式。输入只需能组成 Rust 的 token 流并符合宏自己的文法,因此可以接收点号分隔的函数名等自定义输入。
相关卡片 [[扩展时重发原结构体]]、[[按输入与改写范围选宏]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Hiding information and creating mini-DSLs with function-like macros 函数式过程宏的接口 · 查看原书依据
Instead of decorating a struct with the derive annotation, we call a function-like macro by writing its name followed by an exclamation mark and passing on useful data between parentheses. This is similar to how a declarative macro is used, which also means it can be hard to see the difference between these two. And to make the two even more indistinguishable, Rust also allows you to choose between parentheses, square brackets, and curly braces for arguments.