Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: 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(),
))
2 posts - 2 participants
🏷️ Rust_feed