Immediately instantiated struct definition

⚓ Rust    📅 2025-08-07    👤 surdeus    👁️ 5      

surdeus

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(),
            ))

2 posts - 2 participants

Read full topic

🏷️ Rust_feed