No, there is no way to implement one trait for multiple structs at the same time without metaprogramming like macros.
I'd go so far as to say that there's no reason to, either. If you actually had "the methods doing exactly the same", then you should extract the common member variables into a different struct and implement the trait for that struct (if you even need the trait anymore). You can then add the new struct as a member of the originals.
If you had something like
struct Dog {
hunger: u8,
wagging: bool,
}
struct Cat {
hunger: u8,
meowing: bool,
}
trait Hungry {
fn is_hungry(&self) -> bool;
}
You could have
struct Dog {
hunger: Hunger,
wagging: bool,
}
struct Cat {
hunger: Hunger,
meowing: bool,
}
struct Hunger {
level: u8,
}
impl Hunger {
fn is_hungry(&self) -> bool {
self.level > 100
}
}
If you needed the trait for other reasons, you can just delegate it:
trait Hungry {
fn is_hungry(&self) -> bool;
}
impl Hungry for Hunger {
fn is_hungry(&self) -> bool {
self.level > 100
}
}
impl Hungry for Dog {
fn is_hungry(&self) -> bool { self.hunger.is_hungry() }
}
impl Hungry for Cat {
fn is_hungry(&self) -> bool { self.hunger.is_hungry() }
}
These last two implementations are still the same, but it's a minimal amount of duplication. Even then, I still hold out hope for a form of delegation to be introduced at the syntax level.