知识卡片
用块容纳生成的辅助函数
let composed = compose!(...); 的右侧需要完整表达式,但组合宏还要提供一个辅助函数。用花括号发出块表达式,先在块内声明 compose_two,把最终调用写为无尾分号的最后一个表达式。这样整个块产生一个可绑定给 composed 的闭包。
辅助函数每次展开都在不同的局部作用域,同名不会因为这些宏调用出现在同一外部作用域而相撞。过程宏 crate 只能公开导出过程宏。若希望多个调用复用辅助函数,可用普通库导出辅助函数并重导出宏,由生成代码引用该函数。
相关卡片 [[逆向生成顺序执行的组合]]、[[区分展开复制与单态化]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Hiding information and creating mini-DSLs with function-like macros 辅助函数的作用域与编译成本 · 查看原书依据
Putting the compose_two function inside the block scope has an additional advantage in that it hides the function declaration from other parts of our code. Remember, we are creating this output for every invocation of our macro.
参考来源
- 位置:《Write Powerful Rust Macros》第05章《Hiding information and creating mini-DSLs with function-like macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-5.xhtml#p78)
- 结论依据:第 5.3 节说明额外花括号让声明与调用处于一个表达式中,再比较每处生成辅助函数与由外层库导出的办法。
- 原始内容:Putting the compose_two function inside the block scope has an additional advantage in that it hides the function declaration from other parts of our code. Remember, we are creating this output for every invocation of our macro.