How to implement a hashmap of vectors of any type?

Hi, I'm learning Rust and I decided to try and implement a simple and naive ECS. So I have a structure that looks similar to this:

pub struct World {
    systems: Vec<Box<System>>,
    pub resources: Resources,
    pub components: HashMap<TypeId, Vec<T>>
}

And I want to save components of the same type in each Vec depending on their TypeId. Using a generic T there of course forces me to define a generic on the World structure which is no good. I tried using Any but I can't without wrapping it in a Box and my understanding is that with a Box I will have a layer of indirection, meaning I would save a vector of pointers instead of vector of structs.

What I don't fully understand is why do I need a known size in that inner vector? From the book I gathered that a vec's data is stored on the heap and the vec struct on the stack keeps a pointer to that data. And since it's already on the heap why do I need an additional pointer (Box) to point to my actual data?

I tried looking at https://github.com/slide-rs/specs but it's way over my head.

The additional pointer is to create a trait object, which provides the necessary type erasure to store heterogeneous types in an otherwise homogeneous container.

Your case sounds a bit like this recent thread, and you may be able to use the same approach of storing an entire Vec behind a fat ptr rather than each element in the vec.

2 Likes

Just read that thread, it's exactly what I needed. Thanks!

1 Like