Reputation: 1823
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
?
Upvotes: 4
Views: 2098
Reputation: 1823
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);
}
Upvotes: 1
Reputation: 432059
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;
Upvotes: 5