Vector of Generic Structs in Rust
generics, rust
Solution
Create a trait that each `ComponentList<T>` will implement but that will hide that `T`. In that trait, define any methods you need to operate on the component list (you will not be able to use `T`, of course, you'll have to use trait objects like `&Component`).
trait AnyComponentList {
// Add any necessary methods here
}
impl<T: Component> AnyComponentList for ComponentList<T> {
// Implement methods here
}
struct ComponentManager {
component_lists: Vec<Box<AnyComponentList>>,
}
If you would like to have efficient lookup of a `ComponentList<T>` based on `T` from the `ComponentManager`, you might want to look into `anymap` or `typemap` instead. `anymap` provides a simple map keyed by the type (i.e. you use a type `T` as the key and store/retrieve a value of type `T`). `typemap` generalizes `anymap` by associated keys of type `K` with values of type `K::Value`.
Problem
I am creating an entity component system in Rust, and I would like to be able to store a `Vec` of components for each different `Component` type: ``` pub trait Component {} struct ComponentList<T: Component> { components: Vec<T>, } ``` Is it possible to create a collection of these `ComponentList`s? ``` struct ComponentManager { component_lists: Vec<ComponentList<_>>, // This does not work } ``` This is intended to make it faster to retrieve a list of a certain `Component` type, as all instances of a certain type of component will be in the same `ComponentList`.