Skip to content

Instantly share code, notes, and snippets.

@flagoworld
Created July 21, 2015 04:33
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 flagoworld/c432ac12df37dad5c6f3 to your computer and use it in GitHub Desktop.
Save flagoworld/c432ac12df37dad5c6f3 to your computer and use it in GitHub Desktop.
gstore multi type hashmap
use std::any::Any;
use std::collections::HashMap;
use std::fmt;
pub struct GStore
{
map: HashMap<String, Box<Any>>
}
impl GStore
{
pub fn new() -> GStore
{
GStore { map: HashMap::new() }
}
pub fn insert_string(&mut self, key: &str, string: String)
{
self.map.insert(key.to_string(), Box::new(string));
}
pub fn insert_int(&mut self, key: &str, integer: usize)
{
self.map.insert(key.to_string(), Box::new(integer));
}
pub fn get_string(&self, key: &str) -> &str
{
&self.map.get(key).unwrap().downcast_ref::<String>().unwrap()
}
pub fn get_int(&self, key: &str) -> usize
{
*self.map.get(key).unwrap().downcast_ref::<usize>().unwrap()
}
pub fn contains_key<T: Any>(&self, key: &str) -> bool
{
self.map.get(key).and_then({ |v| v.downcast_ref::<T>() }).map_or(false, { |_| true })
}
}
impl fmt::Debug for GStore
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
write!(f, "GStore ({})", self.map.len())
}
}
fn main()
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment