pub trait A<'a> {
type R: R + 'a;
type S: S + 'a;
}
Suppose I want to create a struct that holds something that implements the A trait:
pub struct B<'a> {
a: &dyn A<'a>,
}
but I want B::new(u8 type) to dynamically decide which object it's gonna hold in the a field, based on the value of type. Since A has these custom types R and S, I couldn't find a way to make this thing compile. Is it possible to do what I want? If there was no dependent types, I guess yes, but with dependent types, I don't know.
No, trait objects must specify the value of all associated types.
error[E0191]: the value of the associated types `R` (from trait `A`), `S` (from trait `A`) must be specified
--> src/lib.rs:9:16
|
5 | type R: R + 'a;
| --------------- `R` defined here
6 | type S: S + 'a;
| --------------- `S` defined here
...
9 | a: &'a dyn A<'a>,
| ^^^^^ help: specify the associated types: `A<'a, R = Type, S = Type>`
You could perhaps simulate it by not using associated types and having the A trait contain a new_r method that produces a dyn R.