Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 813
rincewind Avatar asked Dec 11 '18 01:12

rincewind


1 Answers

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?
like image 199
Shepmaster Avatar answered Oct 07 '22 04:10

Shepmaster