Skip to content

Instantly share code, notes, and snippets.

@reu
Created April 12, 2022 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reu/13a24e3447a39bb56a6fa810c78f6343 to your computer and use it in GitHub Desktop.
Save reu/13a24e3447a39bb56a6fa810c78f6343 to your computer and use it in GitHub Desktop.
Rust AnyMap
use std::any::{Any, TypeId};
use std::collections::HashMap;
#[derive(Default)]
pub struct AnyMap {
map: HashMap<TypeId, Box<dyn Any>>,
}
impl AnyMap {
pub fn insert<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>())
.and_then(|value| value.downcast_ref())
}
}
#[test]
fn test() {
let mut map = AnyMap::default();
map.insert("lol");
map.insert(5 as usize);
assert_eq!(Some(&"lol"), map.get::<&str>());
assert_eq!(Some(&5), map.get::<usize>());
assert_eq!(None, map.get::<u8>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment