Created
November 30, 2017 05:44
-
-
Save U007D/b3c49fff0fc2f7a7941d3df642e4eae2 to your computer and use it in GitHub Desktop.
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
| extern crate libc; | |
| use std::collections::HashMap; | |
| use std::any::TypeId; | |
| use std::string::ToString; | |
| use std::any::Any; | |
| use std::io::{self, Write}; | |
| use libc::{EXIT_SUCCESS, EXIT_FAILURE}; | |
| type Result<T> = std::result::Result<T, Box<std::error::Error>>; | |
| fn main() { | |
| std::process::exit( | |
| match run() { | |
| Ok(ref msg) => { | |
| writeln!(&mut io::stdout(), "{:?}", msg).expect("Panic: error writing to std::io::stdout"); | |
| EXIT_SUCCESS | |
| }, | |
| Err(ref err) => { | |
| writeln!(&mut io::stderr(), "Error: {}", err).expect("Panic: error writing to std::io::stderr"); | |
| EXIT_FAILURE | |
| }, | |
| } | |
| ) | |
| } | |
| struct RecoverableType(TypeId, Box<Any>); | |
| struct ContainerBuilder { | |
| map: HashMap<TypeId, RecoverableType>, | |
| } | |
| impl ContainerBuilder { | |
| fn new() -> Self { Self { map: HashMap::new() } } | |
| fn register_type_as_trait<T: 'static + Default, I: 'static>(&mut self) -> &mut Self { | |
| self.map.insert(TypeId::of::<I>(), RecoverableType(TypeId::of::<T>(), Box::new(T::default()))); | |
| self | |
| } | |
| fn resolve_trait<I: 'static>(&self) -> Option<i64> { | |
| match self.map.get(&TypeId::of::<I>()) { | |
| Some(v) => { | |
| match v.1.downcast_ref::<i64>() { | |
| Some(v) => Some(*v), | |
| None => None, | |
| } | |
| }, | |
| None => None, | |
| } | |
| } | |
| } | |
| fn run() -> Result<()> { | |
| let mut cb = ContainerBuilder::new(); | |
| cb.register_type_as_trait::<i64, Box<ToString>>(); | |
| let my_instance = cb.resolve_trait::<Box<ToString>>().ok_or::<String>("std::option::None encountered unexpectedly".to_string()); | |
| Ok(()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment