Advertisement
Guest User

Untitled

a guest
Aug 29th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.78 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use std::any::Any;
  3.  
  4. trait FirstTrait {
  5.     fn get_name(&self) -> &String;
  6. }
  7. trait SecondTrait {
  8.     fn get_second_name(&self) -> &String;
  9. }
  10.  
  11. struct First {
  12.     name: String,
  13. }
  14.  
  15. impl FirstTrait for First {
  16.     fn get_name(&self) -> &String {
  17.         &self.name
  18.     }
  19. }
  20.  
  21. struct Second {
  22.     name: String,
  23. }
  24.  
  25. impl FirstTrait for Second {
  26.     fn get_name(&self) -> &String {
  27.         &self.name
  28.     }
  29. }
  30.  
  31. impl SecondTrait for Second {
  32.     fn get_second_name(&self) -> &String {
  33.         &self.name
  34.     }
  35. }
  36.  
  37. struct Holder<'a> {
  38.    services: HashMap<std::any::TypeId, &'a Box<Any>>,
  39. }
  40.  
  41. impl<'a> Holder<'a> {
  42.     fn new() -> Holder<'a> {
  43.        Holder { services: HashMap::new() }
  44.    }
  45.    fn register(&mut self, id: std::any::TypeId, service: &'a Box<Any>) {
  46.         self.services.insert(id, service);
  47.     }
  48.     fn get(&self, id: std::any::TypeId) -> &Box<Any> {
  49.         self.services.get(&id).unwrap()
  50.     }
  51. }
  52.  
  53. fn main() {
  54.     let a = Box::new(First { name: "First".to_string() });
  55.     let b = a as Box<FirstTrait>;
  56.     let typeid = get_type_id(&b);
  57.     let c: Box<Any> = Box::new(b);
  58.  
  59.     let a1 = Box::new(Second { name: "Second".to_string() });
  60.     let b1 = a1 as Box<SecondTrait>;
  61.     let typeid1 = get_type_id(&b1);
  62.     let c1: Box<Any> = Box::new(b1);
  63.  
  64.     let mut h = Holder::new();
  65.     h.register(typeid, &c);
  66.     h.register(typeid1, &c1);
  67.    
  68.     let gg = h.get(typeid);
  69.     let g = gg.downcast_ref::<Box<FirstTrait>>().unwrap();
  70.     println!("{}", g.get_name());
  71.    
  72.     let gg1 = h.get(typeid1);
  73.     let g1 = gg1.downcast_ref::<Box<SecondTrait>>().unwrap();
  74.     println!("{}", g1.get_second_name());
  75.    
  76. }
  77.  
  78. fn get_type_id<T: std::any::Any>(_: &T) -> std::any::TypeId {
  79.     std::any::TypeId::of::<T>()
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement