小编tot*_*olo的帖子

在 Rust 中存储具有泛型类型参数的异构类型的集合

我正在尝试在 Rust 中实现一个基本的ECS。我想要一个数据结构,为每个组件存储该特定组件的存储。因为有些组件很常见,而有些则很少,所以我需要不同类型的存储策略,例如VecStorage<T>HashMapStorage<T>

由于游戏引擎的 ECS 不知道组件,我想出了:

trait AnyStorage: Debug {
    fn new() -> Self
    where
        Self: Sized;
}

#[derive(Default, Debug)]
struct StorageMgr {
    storages: HashMap<TypeId, Box<AnyStorage>>,
}
Run Code Online (Sandbox Code Playgroud)

使用VecStorageHashMapStorage<T>实现AnyStorage特性。既然AnyStorage不知道T,我添加了一个由两个具体存储实现的特性:ComponentStorage<T>.

虽然我能够注册新组件(即Box<AnyStorage>StorageMgr's 中storages),但我没有找到插入组件的方法。

这是错误的代码:

pub fn add_component_to_storage<C: Component>(&mut self, component: C) {
    let storage = self.storages.get_mut(&TypeId::of::<C>()).unwrap();
    // storage is of type: &mut Box<AnyStorage + 'static>

    println!("{:?}", storage); // Prints …
Run Code Online (Sandbox Code Playgroud)

rust

4
推荐指数
1
解决办法
1646
查看次数

标签 统计

rust ×1