Feasibility of a macro to lift trait method bodies into struct methods

โš“ Rust    ๐Ÿ“… 2026-02-18    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 1      

surdeus

Hi all,

Iโ€™m wondering if something like this is possible in Rust. I want a macro that can take a trait implementation and โ€œliftโ€ all the method bodies into the struct itself, leaving the trait methods as simple forwarding shims.

Conceptually, Iโ€™m imagining something like:

#[derive(MethodLifter)]
impl MyTrait for MyStruct {
    fn my_fun(&self) {
        println!("true implementation");
        let x = 1 + 2 + 39;
        x
    }
}

And the macro would transform it into:

impl MyStruct {
    fn my_fn(&self) -> usize {
        println!("true implementation");
        let x = 1 + 2 + 39;
        x
    }
}

impl MyTrait for MyStruct {
    fn my_fn(&self) -> usize{
        println!("shim called"); // the debug print is not necessary 
        MyStruct::my_fn(self)
    }
}

The reason for this outrageous hack is quite simple, the goal is to make it easier to call these methods in GDB, where I couldn't figure out how to call trait methods (I believe it's not yet possible?).

I understand this would have limitations (e.g., name collisions), and thatโ€™s acceptable.

Would something like this be feasible with Rustโ€™s macro system?

Playground link with an example: Rust Playground

2 posts - 2 participants

Read full topic

๐Ÿท๏ธ Rust_feed