知识卡片
局部绑定具有卫生性
macro_rules! 的局部变量和标签使用与定义关联的语法上下文,降低同名造成的误捕获。宏体自己生成 let x = 0 时,调用端随手写一个同名 x 无法引用这个宏绑定。调用者需要协作时,可把名字作为 ident 传给宏。声明式宏属于混合位置卫生,其他名字仍需考虑调用位置、路径和可见性。
相关卡片 [[宏和依赖各有作用域]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
- · 柯里化与卫生性
原书出处 · 1 处
- Declarative macros 柯里化与卫生性 · 查看原书依据
You should be aware that not everything you generate will be added as is to your code because declarative macros have a concept of hygiene for identifiers. Simply put, identifiers inside your macro will always be different from those in code outside the macro, even if their names overlap, which means a number of things are impossible.
参考来源
- 位置:《Write Powerful Rust Macros》第02章《Declarative macros》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-2.xhtml#p151)
- 结论依据:原文用 generate_x 无法在外部按拼写访问的例子解释卫生性和显式传名。
- 原始内容:You should be aware that not everything you generate will be added as is to your code because declarative macros have a concept of hygiene for identifiers. Simply put, identifiers inside your macro will always be different from those in code outside the macro, even if their names overlap, which means a number of things are impossible.