4

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?

madeinQuant
  • 1,721
  • 1
  • 18
  • 29

2 Answers2

5

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;
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
1

I found there are some errors with my original macro when I assign a new value to the variable. With this modified macro, based on @Shepmaster's suggestion, I can assign a new value to the variables defined by the macro:

macro_rules! double {
    ( $($var:ident),+) => {
        $(let mut $var: f64;)+
    };
}

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

    FT = 2.0;
    println!("{}", FT);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
madeinQuant
  • 1,721
  • 1
  • 18
  • 29