0

I have a trait Service defined as follows:

trait Service {
    fn do_something(&self);
}

Service is implemented by another trait, FancyService:

trait FancyService {
    fn fancy(&self) -> i32;
    fn do_something_fancy(&self, t: i32);
}

impl Service for FancyService {
    fn do_something(&self) {
        let t = self.fancy();

        self.do_something_fancy(t);
    }
}

Finally I have a struct that implements FancyService:

struct MyFancyService {
    t: i32
}

impl FancyService for MyFancyService {
    fn fancy(&self) -> i32 { self.t }
    fn do_something_fancy(&self, t: i32) { println!("t: {}", t); }
}

The idea is MyFancyService should now also implement Service and thus I should be able to put it in a Box<Service>, like this:

let s: Box<Service> = Box::new(MyFancyService { t: 42 });

This doesn't compile. Rust complains that MyFancyService:

   |
28 |     let s: Box<Service> = Box::new(MyFancyService { t: 42 });
   |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Service` is not implemented for `MyFancyService`
   |
   = note: required for the cast to the object type `Service`

Given that MyFancyService implements FancyService which implements Service, why doesn't MyFancyService implement Service?

Sample code in the playground.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Tim
  • 4,560
  • 2
  • 40
  • 64
  • See also: [Why would I implement methods on a trait instead of as part of the trait?](https://stackoverflow.com/q/34438755/155423) – Shepmaster Dec 07 '17 at 21:13
  • I oversimplified my question into a duplicate. Is there a question that covers this case, but where `FancyService` and `MyFancyService` are generic? – Tim Dec 07 '17 at 21:16
  • Can you expand a bit more on what you mean by "generic" in this case? I don't know what it would mean to implement a "generic" trait for a "generic" type... – Shepmaster Dec 07 '17 at 21:25
  • @Shepmaster. Thanks for asking, I was able to figure it out. I needed to use associated types instead of making my trait generic. – Tim Dec 07 '17 at 21:45
  • Ah, so the second answer on the linked duplicate then? – Shepmaster Dec 07 '17 at 22:10
  • I don't remember what got me to look at associated types. But your question [When is it appropriate to use an associated type versus a generic type?](https://stackoverflow.com/questions/32059370/when-is-it-appropriate-to-use-an-associated-type-versus-a-generic-type), and the associated answer helped me greatly in figuring out when to use what feature. – Tim Dec 08 '17 at 01:08

0 Answers0