1

I was wondering how I could have a macro generating a struct with fields names created partly from the macro's params :

#[macro_export]
macro_rules! my_macro {
    ($($comp:ident),+) => {
        {
            struct MyStruct {
                $(
                    field1_$comp: $comp,
                    field2_$comp: usize,
                )+
            }

            MyStruct {
                $(
                    field1_$comp: $comp::default(),
                    field2_$comp: 0,
                )+
            }
        }
    };
}

This doesn't work, with the error "expected : or ;". Is there a way to generate field names with the params ?

I would like something like :

my_macro!(f32, f64);

would expand to :

MyStruct {
    field1_f32: f32,
    field2_f32: usize,
    field1_f64: f64,
    field2_f64: usize
}
  • 1
    Does this answer your question? [Is it possible to declare variables procedurally using Rust macros?](https://stackoverflow.com/questions/23061702/is-it-possible-to-declare-variables-procedurally-using-rust-macros) Or this? [Can a Rust macro create new identifiers?](https://stackoverflow.com/questions/27415011/can-a-rust-macro-create-new-identifiers) – Caesar Aug 20 '22 at 12:24

1 Answers1

1

Both the commented answers are valid options, but they use another macros or the nightly compiler. What I've done instead, is to use only $comp as a name, and pack every field I wanted in another struct like so :

#[macro_export]
macro_rules! my_macro {
    ($($comp:ident),+) => {
        {
            struct SomeOtherStruct<T> {
                field1: T,
                field2: usize,
            }
            struct MyStruct {
                $(
                    $comp: SomeOtherStruct<$comp>,
                )+
            }

            MyStruct {
                $(
                    $comp: SomOtherStruct::<$comp> {
                        field1: $comp::default(),
                        field2: 0,
                    }
                )+
            }
        }
    };
}