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.