SHARE
TWEET

Untitled

a guest Jul 21st, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::any::{Any, TypeId};
  2. use std::collections::HashMap;
  3.  
  4. struct AnyMap {
  5.     inner: HashMap<TypeId, Box<Any>>,
  6. }
  7.  
  8. impl AnyMap {
  9.     fn new() -> Self {
  10.         AnyMap { inner: Default::default() }
  11.     }
  12.    
  13.     fn insert<T: 'static>(&mut self, value: T) {
  14.         self.inner.insert(value.type_id(), Box::new(value));
  15.     }
  16.    
  17.     fn get<T: 'static>(&self) -> Option<&T> {
  18.         self.inner.get(&TypeId::of::<T>()).and_then(|x| x.downcast_ref())
  19.     }
  20. }
  21.  
  22. fn main() {
  23.     let mut map = AnyMap::new();
  24.     map.insert(1i32);
  25.     map.insert(String::from("foobar"));
  26.     println!("{:?}", map.get::<i32>());
  27.     println!("{:?}", map.get::<bool>());
  28.     println!("{:?}", map.get::<String>());
  29. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top