Feasibility of a macro to lift trait method bodies into struct methods
โ Rust ๐ 2026-02-18 ๐ค surdeus ๐๏ธ 1Hi 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
๐ท๏ธ Rust_feed