0

Consider this snippet:

struct Foo(i32);

trait MetaTrait {
    fn generic(&self, n: i32);
}

trait MyTrait {
    fn my_method(&self, x: i32);
}

impl MetaTrait for MyTrait {
    fn generic(&self, x: i32) {
        self.my_method(x);
    }
}

impl MyTrait for Foo {
    fn my_method(&self, n: i32) {
        println!("doing something with {}", n);
    }
}

fn my_dynamic_fun<T: MetaTrait + ?Sized>(arg: &T) {
    arg.generic(100);
}

fn main() {
    let foo = Foo(42);
    my_dynamic_fun(&foo);
}

It gives the error:

  --> src/main.rs:30:5
   |
30 |     my_dynamic_fun(&foo);
   |     ^^^^^^^^^^^^^^ the trait `MetaTrait` is not implemented for `Foo`
   |

Instead an explicit type cast works:

my_dynamic_fun(&foo as &MyTrait);

Probably I've not completely grasped the concept of a trait implementation for a trait ... but why the compiler is not able to infer that a Foo implements MyTrait that implements MetaTrait?

attdona
  • 17,196
  • 7
  • 49
  • 60
  • 5
    Try `impl MetaTrait for T where T: MyTrait`. – ljedrz Apr 13 '18 at 12:08
  • 1
    @Tom Regner: probably the title is too generic but this question has to do with trait objects, I don't think it is a duplication. – attdona Apr 13 '18 at 12:24
  • 1
    @attdona the issue and the possible solutions in the duplicate are the same; `(&jim as &HasBed).sleep();` and `(&jane as &HasTent).sleep();` would also work there. – ljedrz Apr 13 '18 at 12:58
  • Thanks! At first it was not obvious for me. Now it is clear, thanks also to @Tom Regner. I will mark as duplicate. – attdona Apr 13 '18 at 13:04

0 Answers0