Derive Macro of generic Trait
⚓ Rust 📅 2025-10-20 👤 surdeus 👁️ 2I wanted to create a derived macro of a trait to ensure that I could retrieve important values from my windows. This is the trait:
pub trait WindowValues<B>: 'static + Sized + Component + Default
where
B: 'static + Sized + Hash + Component + Clone + EnumWindowColor + States,
{
fn get_height(&self) -> f32;
fn get_left(&self) -> f32;
fn get_width(&self) -> f32;
fn get_button(&self) -> B;
}
That's how I regularly use it:
#[derive(Component)]
pub struct CreditsWindow(f32, f32, f32, Buttons);
impl WindowValues<Buttons> for CreditsWindow {
fn get_height(&self) -> f32 {
self.0
}
fn get_left(&self) -> f32 {
self.1
}
fn get_width(&self) -> f32 {
self.2
}
fn get_button(&self) -> Buttons {
self.3.clone()
}
}
impl Default for CreditsWindow {
fn default() -> Self {
Self(15.0, 15.0, 0.5, Buttons::Credits)
}
}
This is a derivable macro, I've implemented myself:
#[proc_macro_derive(TextInfo)]
pub fn derive_text_info(input: TokenStream) -> TokenStream {
let name = parse_macro_input!(input as DeriveInput).ident;
TokenStream::from(quote! {
impl TextInfo for #name {
fn get_x(&self) -> f32 {self.0}
fn get_y(&self) -> f32 {self.1}
fn get_name(&self) -> String {self.2.clone()}
}
})
}
The problem for me now is that I haven't quite figured out how to derive a generic one from my previous experience with procedural macros.
1 post - 1 participant
🏷️ Rust_feed