16

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
rincewind
  • 1,103
  • 8
  • 29

1 Answers1

17

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:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366