简体   繁体   中英

Vector of Generic Structs in 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 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 .

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 (ie 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM