Created
July 25, 2016 21:40
-
-
Save anonymous/b8983b5dfc9e78376a623fece7cd6d53 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains hidden or 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; | |
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