Skip to content

Instantly share code, notes, and snippets.

Created July 25, 2016 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/b8983b5dfc9e78376a623fece7cd6d53 to your computer and use it in GitHub Desktop.
Save anonymous/b8983b5dfc9e78376a623fece7cd6d53 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
use std::any::Any;
use std::collections::HashMap;
use std::fmt::Debug;
fn main() {
let mut map: HashMap<(), Box<Fn() -> Box<Any>>> = HashMap::new();
map.insert((), Box::new(|| {
let val: Box<Box<Trait>> = Box::new(Box::new(A));
val
}));
let test = Test {
map: map,
};
let a: Option<Box<Box<Trait>>> = test.get::<Box<Trait>>();
println!("{:?}", a);
}
struct Test {
map: HashMap<(), Box<Fn() -> Box<Any>>>,
}
impl Test {
fn get<T: Any>(&self) -> Option<Box<T>> {
let result = self.map.get(&());
match result {
Some(value) => {
let returned = value.as_ref()();
Some(returned.downcast::<T>().unwrap())
},
None => None,
}
}
}
#[derive(Debug)]
struct A;
trait Trait: Debug {}
impl Trait for A {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment