Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of Generic Structs in Rust

Tags:

generics

rust

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 ComponentLists?

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.

like image 295
EpicPotato Avatar asked Oct 15 '16 22:10

EpicPotato


People also ask

What is a VEC in Rust?

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'

What does generic mean in Rust?

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.


1 Answers

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.

like image 165
Francis Gagné Avatar answered Oct 21 '22 16:10

Francis Gagné