Minimalist anymap?

Can anyone provide a minimalist implementation of https://github.com/chris-morgan/anymap ? Something that has:

pub struct MyAnyMap {}

impl MyAnyMap {
  pub fn put<T>(&mut self, t: T) { ... }
  pub fn get<T>(&self) -> Option<T> { ... }
}

This goal here is pedagogical, I would like to understand the key idea used to implement this.

use std::any::{Any, TypeId};
use std::collections::HashMap;

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())
    }
}
11 Likes

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.