简体   繁体   English

通用结构传染媒介在铁锈的

[英]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: 我在Rust中创建一个实体组件系统,我希望能够为每个不同的Component类型存储一个Vec Component

pub trait Component {}

struct ComponentList<T: Component> {
    components: Vec<T>,
}

Is it possible to create a collection of these ComponentList s? 是否可以创建这些ComponentList的集合?

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 . 这旨在使检索特定Component类型的列表更快,因为特定类型组件的所有实例将在同一ComponentList

Create a trait that each ComponentList<T> will implement but that will hide that T . 创建一个每个ComponentList<T>将实现但将隐藏该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 ). 在该特性中,定义在组件列表上操作所需的任何方法(您将无法使用T ,当然,您必须使用像&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. 如果你想有一个高效的查找ComponentList<T>基于TComponentManager ,你可能想看看anymaptypemap来代替。 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 ). anymap提供了一个由类型键入的简单映射(即使用类型T作为键并存储/检索类型T的值)。 typemap generalizes anymap by associated keys of type K with values of type K::Value . typemap通过类型K的关联键将anymap概括为类型为K::Value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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