Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::any::{Any, TypeId};
- use std::collections::HashMap;
- struct AnyMap {
- inner: HashMap<TypeId, Box<Any>>,
- }
- impl AnyMap {
- fn new() -> Self {
- AnyMap { inner: Default::default() }
- }
- fn insert<T: 'static>(&mut self, value: T) {
- self.inner.insert(value.type_id(), Box::new(value));
- }
- fn get<T: 'static>(&self) -> Option<&T> {
- self.inner.get(&TypeId::of::<T>()).and_then(|x| x.downcast_ref())
- }
- }
- fn main() {
- let mut map = AnyMap::new();
- map.insert(1i32);
- map.insert(String::from("foobar"));
- println!("{:?}", map.get::<i32>());
- println!("{:?}", map.get::<bool>());
- println!("{:?}", map.get::<String>());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement