知识卡片
按输入与改写范围选宏
决定用哪一种宏时,先看调用位置、输入的语法和允许产生的变化。若已有简单的 token 模式能表达规则,可以先用声明宏。确实需要过程宏时,下面三种接口承诺不同。
| 需求 | 适合的过程宏 | 展开效果 |
|---|---|---|
| 给结构体、枚举或联合补充实现 | 派生宏 #[derive(...)] |
输出追加在原类型之后 |
| 重写一个被标注的项目,例如包装函数体 | 属性宏 #[name(...)] |
输出替换项目 |
| 在宏调用位置接收独立文法并生成所需语法 | 函数式宏 name!(...) |
输出替换调用 |
选择只允许所需范围的机制,调用者更容易预估宏会怎样影响已有代码。函数式宏能接受点号组合等输入,但也把文法、诊断和结果语法的责任交给实现者。
相关卡片 [[函数式宏替换调用]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
- · 按改写范围选择宏
原书出处 · 1 处
- Hiding information and creating mini-DSLs with function-like macros 按改写范围选择宏 · 查看原书依据
that derive macros, the most limited of the three, are perhaps the most popular of the three: a limitation can also be a strength. For instance, derive macros are predictable in their effects, both for users and creators, since they only add without changing or deleting. So if you only want to add functionality to a struct or enum, and the problem is too complex for a declarative macro, you have already found the right
参考来源
- 位置:《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#p90)
- 结论依据:第 5.4 节和图 5.5 按输入、用法与效果对照三种宏,第 5.3 节和总结说明自定义语法及选择最简单方案的成本关系。
- 原始内容:that derive macros, the most limited of the three, are perhaps the most popular of the three: a limitation can also be a strength. For instance, derive macros are predictable in their effects, both for users and creators, since they only add without changing or deleting. So if you only want to add functionality to a struct or enum, and the problem is too complex for a declarative macro, you have already found the right