知识卡片

普通读书笔记卡 · 6074.d.1.a.3.c.3

表达式宏避免重复求值

理解等级:中级

把同一表达式参数在宏体展开两次,会重复副作用,square!中递增变量就不再是对一个值平方。可先把表达式求值一次绑定局部变量,或把输入限制为所需语法类别。卫生规则不能替代求值次数检查,也不会自动消除副作用。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 5. Tooling Declarative Macros · 查看原书依据

      square_once { { $e:expr } => { { let x = $e; x*x // Note: there's a detail here to be explained later... } } } // output now: x = 2, y = 4 The other alternative is not to allow an arbitrary expression as input to the macro. If the expr syntax fragment specifier is replaced with an ident fragment specifier, then the macro will only accept identifiers as input

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第5章《Declarative Macros》(spine9;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch05.html;u141-ch05-009)。 - 结论依据:原文在“square_once”附近的定义、例子或代码支撑本卡核心说明:把同一表达式参数在宏体展开两次,会重复副作用,square!中递增变量就不再是对一个值平方。边界按已读前提解释;示例未执行。 - 原始内容:square_once { { $e:expr } => { { let x = $e; x*x // Note: there's a detail here to be explained later... } } } // output now: x = 2, y = 4 The other alternative is not to allow an arbitrary expression as input to the macro. If the expr syntax fragment specifier is replaced with an ident fragment specifier, then the macro will only accept identifiers as input