Immediately instantiated struct definition

I had an interesting idea for a little macro. Are you aware of any existing crates that do something similar?

/// immediately instantiated type declaration
macro_rules! iitd {
    (
        $(#[$meta:meta])*
        struct $name:ident {
            $($field:ident : $typ:ty),* $(,)?
        }
    ) => {{
        $(#[$meta])*
        struct $name {
            $($field: $typ),*
        }

        $name {
            $($field),*
        }
    }};
}

fn main() {
    let x = 42;
    
    let f = iitd!{
        #[derive(Debug)]
        struct Foo { x: i32 }
    };
    
    println!("{f:?}"); // Foo { x: 42 }

}

It's quite nice for the times you define a struct inline just for functionality from derive attributes.

I came up with it as I was making askama templates. So something like

            Ok(Html(
                crate::iitd! {
                    #[derive(askama::Template)]
                    #[template(path = "package/show.html")]
                    struct PackageDetail {
                        title: String,
                        package: crate::models::Package,
                        features: Vec<String>,
                    }
                }
                .render()
                .unwrap(),
            ))

For this specific use case I’d instead create a macro, which takes the path to the template and the parameters and then crates the struct within a function as an opaque type.

Something like this, possibly more sophisticated, could also be included in the askama crate.

1 Like

SQLx does the same thing internally for their query! macro (and related macros, but not the ones with _as in their name).

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.