问题
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