Why can I not access a variable declared in a macro unless I pass in the name of the variable?

*爱你&永不变心* 提交于 2020-12-29 09:49:26

问题


I have this macro:

macro_rules! set_vars {
    ( $($x:ident),* ) => {
        let outer = 42;
        $( let $x = outer; )*
    }
}                                                                             

Which expands this invocation:

set_vars!(x, y, z);

into what I expect (from --pretty=expanded):

let outer = 42;
let x = outer;
let y = outer;
let z = outer;

In the subsequent code I can print x, y, and z just fine, but outer seems to be undefined:

error[E0425]: cannot find value `outer` in this scope
  --> src/main.rs:11:5
   |
11 |     outer;
   |     ^^^^^ not found in this scope

I can access the outer variable if I pass it as an explicit macro parameter.

Is this intentional, something to do with "macro hygiene"? If so, then it would probably make sense to mark such "internal" variables in --pretty=expanded in some special way?


回答1:


Yes, this is macro hygiene. Identifiers declared within the macro are not available outside of the macro (and vice versa). Rust macros are not C macros (that is, Rust macros are more than glorified text replacement).

See also:

  • The Little Book of Rust Macros
  • A Practical Intro to Macros
  • So, what are hygienic macros anyway?


来源:https://stackoverflow.com/questions/53716044/why-can-i-not-access-a-variable-declared-in-a-macro-unless-i-pass-in-the-name-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!