为另一个特征实现特征

时间:2018-04-13 12:00:16

标签: rust

请考虑以下代码段:

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);
}

它给出错误:

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

而是显式类型转换:

my_dynamic_fun(&foo as &MyTrait);

可能我还没有完全掌握特质的特质实施概念...... 但为什么编译器无法推断Foo实现MyTrait实现MetaTrait

0 个答案:

没有答案