(This is my second try to track down my exact problem. See the edit history)
I have a simple generic Trait and two different implementations:
pub trait MyTrait<T=Self> where T: MyTrait {
}
struct Impl1;
impl MyTrait for Impl1 {
}
struct Impl2;
impl MyTrait for Impl2 {
}
I now want a vector that contains elements of both implementations. As I learned here, I do:
fn foo() {
let mut traits: Vec<Box<MyTrait>> = Vec::new();
traits.push(Box::new(Impl1{}));
traits.push(Box::new(Impl2{}));
}
But the compiler doesn't agree:
error[E0393]: the type parameter `T` must be explicitly specified
--> src/main.rs:25
|
25 | let mut traits: Vec<Box<MyTrait>> = Vec::new();
| ^^^^^^^ missing reference to `T`
|
= note: because of the default `Self` reference, type parameters must be specified on object types
On the one hand, that makes sense. On the other hand, what should I put for T
? I want this to be generic, so I can't simply put there Impl1
or Impl2
. I could do Vec<Box<MyTrait<MyTrait>>>
, but this will only move the error, not resolve it.
Edit
The code above is the minimal failing one, here's a slightly less minimal implementation:
enum MyEnum<T: MyTrait> {
A(T),
B
}
pub trait MyTrait<T=Self> where T: MyTrait {
fn do_stuff(self) -> MyEnum<T>;
}
struct Impl1;
impl MyTrait for Impl1 {
fn do_stuff(self) -> MyEnum<Impl1> {
MyEnum::A(self)
}
}
struct Impl2;
impl MyTrait for Impl2 {
fn do_stuff(self) -> MyEnum<Impl2> {
MyEnum::B
}
}
Each MyTrait
object consumes itself and can either result in a MyEnum::A
containing another MyTrait
object or a MyEnum::B
.