All types must be statically known at compile time. If Rust would allow different associated types for elements of a Vec
, type information could depend on indices which are only known at runtime.
I find it helpful to consider a smaller example:
trait Behaviour {
type T;
fn make_t(&self) -> T;
}
fn foo(my_vec: Vec<&dyn Behaviour>, index: usize) {
let t = my_vec[index].make_t(); //Type of t depends on index
}
You were on the right track to fixing this though. I assume you introduced the SubBehaviour
trait because you realized you need to put restrictions of what T
can be. The thing is, in that case you don't need an associated type anymore.
trait SubBehaviour {}
trait Behaviour {
fn make_t(&self) -> Box<dyn SubBehaviour>;
fn ref_t(&self) -> &dyn SubBehaviour; // also fine
}
fn some_function(my_vec: Vec<&dyn Behaviour>, index: usize) {
let t1 = my_vec[index].make_t();
}
The only limitation is that in your definition of Behaviour
you can not do anything which would depend on the size of T
, (like allocating it on the stack or moving it) since the size of T
can not be specified by the SubBehaviour
trait.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…