5

I have trait FooTrait which has a bunch of functions. I also have structs FooStruct and BarStruct and want to implement FooTrait for both structs with the methods doing exactly the same.

Is there a way to implement FooTrait for both FooStruct and BarStruct at once? I imagined something like the following:

impl FooTrait for FooStruct + BarStruct {
    // implement methods here
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Zonico
  • 192
  • 1
  • 11

1 Answers1

10

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366