Optional generics in struct creating macro

Hi,

I have the following macro:

macro_rules! create_struct {
    (struct $name:ident {
        $($field_name:ident: $field_type:ty,)*
    }) => {
        
        pub struct $name {
            demo: String,
            $($field_name: $field_type,)*
        }

    }
}

I can use it like this:

create_struct!(struct Test {});

It'd be really convenient to be able to add lifetimes or generic types in general to the struct created by the macro call.
Like this:

create_struct!(struct Test<'a> {});

How would I go about implementing such a functionality?
Thanks in advance :slight_smile:!

Something like this would work :

macro_rules! create_struct {
    (struct $name:ident $(<$($generics:tt),*>)? {
        $($field_name:ident: $field_type:ty,)*
    }) => {
        
        pub struct $name $(<$($generics),*>)? {
            demo: String,
            $($field_name: $field_type,)*
        }

    }
}

create_struct!(struct Test1 {});

create_struct!(struct Test2<'a, T> {
    reference: &'a T,
});

It uses generics:tt in order to capture both types and lifetimes.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.