How can I write a macro that implements the same methods for multiple structs? The methods should be slightly different based on the struct.
The code should look something like this:
macro_rules! say_name {
(for $($t:ty),+) => {
$(impl $t {
fn say_name(&self) {
//if $t == A then self.say_a();
//if $t == B then self.say_b();
}
})*
};
}
struct A {
}
impl A {
fn say_a(&self) {
println!("A");
}
}
struct B {
}
impl B {
fn say_b(&self) {
println!("B");
}
}
say_name!(for A, B);
fn main() {
let a = A {};
let b = B {};
a.say_name();
b.say_name();
}
My code is a little bit complicated so I provided a dummy code for the purpose of the question.
You can define a trait next to the macro definition that the macro definition can use, and which "specializes" for A or B:
Playground