I want to create a variable that holds a trait. The trait implementation is unknown during compile time. Hence, I need a trait object. This works with "normal" traits but not when the trait has an associated type that is unknown during compile time.
Why? Let AssTrait
be a trait associating a type and AssTraitImpl
a struct implementing that trait (see example below). Now a trait object for an instance of AssTraitImpl
could just point to the vtable representing the methods implemented for AssTraitImpl
. Or am I wrong?
Example
The code below is not working. However it is, if we remove the associated type from the trait.
trait AssTrait {
type Item;
}
struct AssTraitImpl {
}
impl AssTrait for AssTraitImpl {
type Item = i32;
}
fn main() {
let var: &dyn AssTrait;
}
I get this error message:
error[E0191]: the value of the associated type `Item` (from trait `AssTrait`) must be specified
--> src/main.rs:20:20
|
9 | type Item;
| --------- `Item` defined here
...
20 | let var : &dyn AssTrait;
| ^^^^^^^^ help: specify the associated type: `AssTrait<Item = Type>`