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
?