本文介绍了通用结构在锈的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rust中创建了一个实体组件系统,我希望能够为每个不同的组件存储 Vec 组件。 / code> type:

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>,
}

创建这些 ComponentList的集合 s?

struct ComponentManager {
    component_lists: Vec<ComponentList<_>>, // This does not work
}

这是为了更快地检索某个组件类型的列表,因为某个类型的组件的所有实例都在同一个 ComponentList 。

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.

推荐答案

创建每个 ComponentList< T> 会执行,但会隐藏 T 。在这个特质中,定义你需要在组件列表上操作的任何方法(你将不能使用 T ,当然,你必须使用特质对象& Component )。

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>>,
}






如果您想有效查找<$ c $根据 ComponentManager 中的 T ,您可能想要使用c> ComponentList< T> 查看或。 anymap 提供了一个简单的映射(即你使用类型 T 作为键并存储/检索类型 T 的值)。 typemap 概括 anymap 通过类型 K 类型为 K :: Value 。


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.

这篇关于通用结构在锈的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 15:53