【问题标题】:Vector of Generic Structs in RustRust 中的泛型结构向量
【发布时间】:2016-10-15 22:04:48
【问题描述】:

我正在用 Rust 创建一个实体组件系统,我希望能够为每个不同的 Component 类型存储一个 Vec 组件:

pub trait Component {}

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

是否可以创建这些ComponentLists 的集合?

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

这是为了加快检索特定Component 类型的列表,因为特定类型组件的所有实例都将在同一个ComponentList 中。

【问题讨论】:

  • 您的意思是Vec&lt;ComponentList&lt;C&gt;&gt;,其中C: Component 是整个向量的同一个类,还是Vec&lt;ComponentList&lt;c&gt;&gt; 代表每个组件类型c
  • 我的意思是每个implComponent(后者)都有一个Vec&lt;ComponentList&lt;c&gt;&gt;
  • 在这种情况下,您需要为结构中的每个实现保留一个属性,或者拥有一个具有动态调度的向量(如下面的第一个答案所示)。
  • 你认为你能澄清我将如何准确地为每个实现保留一个属性吗?
  • struct ComponentManager { component1: Component1, component2: Component2, ... }

标签: generics rust


【解决方案1】:

创建一个每个ComponentList&lt;T&gt; 都将实现的特征,但这将隐藏T。在该特征中,定义您需要对组件列表进行操作的任何方法(您将无法使用T,当然,您必须使用像&amp;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>>,
}

如果您想根据TComponentManager 高效查找ComponentList&lt;T&gt;,您可能需要查看anymaptypemapanymap 提供了一个以类型为键的简单映射(即,您使用类型 T 作为键并存储/检索类型为 T 的值)。 typemap 通过 K 类型的关联键和 K::Value 类型的值来概括 anymap

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-24
    • 2022-11-23
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多