1

在我的代码中,我有实现 Trait1 的对象。我还有各种实现 Trait2 的对象,它期望 Trait1 对象作为参数。当我尝试创建满足 Trait2 的对象向量时,出现编译器错误。

我能得到的最简单的复制:

trait Trait1 {
    fn doit(&self);
}

trait Trait2 {
    fn do_other_thing(&self, obj: &impl Trait1);
}

fn main() {
    let mut myvec = Vec::<Box<dyn Trait2>>::new();
}

这导致编译器错误:

error[E0038]: the trait `Trait2` cannot be made into an object
  --> src/main.rs:10:18
   |
5  | trait Trait2 {
   |       ------ this trait cannot be made into an object...
6  |     fn do_other_thing(&self, obj: &impl Trait1);
   |        -------------- ...because method `do_other_thing` has generic type parameters
...
10 |     let mut myvec = Vec::<Box<dyn Trait2>>::new();
   |                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Trait2` cannot be made into an object
   |
   = help: consider moving `do_other_thing` to another trait

有没有办法实现这样的目标?'myvec' 在 Trait2 上必须是动态的,因为我希望拥有实现此 trait 的不同类型。有没有办法让'obj'在 Trait1 上完全通用,或者我必须将它绑定到实现 Trait1 的一种特定类型?

4

0 回答 0