Created
April 12, 2022 22:15
-
-
Save reu/13a24e3447a39bb56a6fa810c78f6343 to your computer and use it in GitHub Desktop.
Rust AnyMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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