Serializing MyAnyMap

  1. This is for pedagogical reasons, please do not respond with "use crate_foo".

  2. Here is current sample code:

pub struct MyAnyMap {
    map: HashMap<TypeId, Box<dyn Any>>,}

impl MyAnyMap {
    pub fn put<T: 'static>(&mut self, t: T) {
        self.map.insert(TypeId::of::<T>(), Box::new(t));}

    pub fn get<T: 'static>(&self) -> Option<&T> {
        self.map
            .get(&TypeId::of::<T>())
            .map(|value| value.downcast_ref().unwrap())}}

I would now like to be able to serialize to file / load from file MyAnyMap. I am fine with using serde/binencode. My main concerns are:

  1. how to deal with TypeId, which I believe can change across Rust releases and

  2. given that everything is stored as 'dyn Any', even if I only put in T: serialize / deserialize, how do we recover that functionality

  1. I'm pretty sure that TypeId is meant to be used as an opaque type - you can't serialize it.
  2. You would have to downcast to a concrete type, then deserialize that type.

I think what you're trying to do isn't possible in the sense that you need to know the type(s) you're expecting to deserialize into a priori. It could be a selection of types (either static or dynamic dispatch) but it can't be completely generic. Others may correct me.

Enums serialize well because they will include a tag to denote the variant. This is how I would handle what you're trying to do.

1 Like

You might be able to set something up using typetag and a custom trait, but I think you'll still run into the problem of not being able to inspect a TypeId.

I think you are right. This alone shoots down the entire idea.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.