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
.
The Vec type allows to access values by index, because it implements the Index trait. An example will be more explicit: let v = vec![ 0, 2, 4, 6]; println!(" {}", v[1]); // it will display '2'
In Rust, generics refer to the parameterization of data types and traits. Generics allows to write more concise and clean code by reducing code duplication and providing type-safety. The concept of Generics can be applied to methods, functions, structures, enumerations, collections and traits.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With