Throughout my code I have objects which implement Trait1. I also have a variety of object which implement Trait2, which expects Trait1 objects as a parameter. When I try to create a vector of objects which fulfill Trait2 I get a compiler error.
Simplest reproduction I could get:
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();
}
Which results in the compiler error:
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
Is there any way to achieve something like this? 'myvec' has to be dynamic on Trait2, since I expect to hold different types which implement this trait. Is there any way to also allow 'obj' to be fully generic on Trait1 or do I have to tie it to one specific type that implements Trait1?