Search code examples
rustrust-macros

"expected identifier" when creating a macro to define mutable variables at the same time


I want to declare multiple mutable variables at the same time. Defined a macro to declare mutable variables as the following.

macro_rules! mutf64 {
    ( $( $e:expr ),+ ) => {
        {
            $(
                let mut $e:f64;
            )+
        }
    };
}

fn main() {
    mutf64!(FT, FX, alpha, H, K, lambda, T, X);
}

There is an error when syntax checking with compiler:

error: expected identifier, found `FT`
  --> src/main.rs:5:25
   |
5  |                 let mut $e:f64;
   |                         ^^ expected identifier
...
12 |     mutf64!(FT, FX, alpha, H, K, lambda, T, X);
   |     ------------------------------------------- in this macro invocation

Why can't I do this with macro_rules?


Solution

  • An expression is not an identifier. Use this instead:

    ( $( $e:ident ),+ ) => {
    

    When declaring variables, you need to provide an identifier. An expression would make no sense:

    let mut 1+1;