知识卡片

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

宏参数不遵循函数调用直觉

理解等级:中级

宏在调用位置展开代码,m!(value)不意味着像普通按值函数那样必然移动value。展开可就地修改传入标识符,也可能执行return或?。应让控制流尽量在调用处可见,例如宏返回Result,由调用者使用?,并清楚记录特殊行为。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

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

      inc_item!(x); println!("x is {x:?}"); x is Item { contents: 43 } This becomes clear if we remember that the macro inserts code at the point of invocation—in this case, adding a line of code that increments x.contents. The cargo-expand tool shows the code that the compiler sees, after macro expansion: let mut x = Item { contents: 42 }; x.contents += 1; { ::st

    参考来源

    - 位置:《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-008)。 - 结论依据:原文在“inc_item!(x)”附近的定义、例子或代码支撑本卡核心说明:宏在调用位置展开代码,m!(value)不意味着像普通按值函数那样必然移动value。边界按已读前提解释;示例未执行。 - 原始内容:inc_item!(x); println!("x is {x:?}"); x is Item { contents: 43 } This becomes clear if we remember that the macro inserts code at the point of invocation—in this case, adding a line of code that increments x.contents. The cargo-expand tool shows the code that the compiler sees, after macro expansion: let mut x = Item { contents: 42 }; x.contents += 1; { ::st