Guest User

Untitled

a guest
Sep 25th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. use std::any::{Any, TypeId};
  2. use std::cell::*;
  3. use std::collections::hash_map::ValuesMut;
  4. use std::collections::{HashMap, HashSet};
  5.  
  6. pub trait TypeErasedTrait: std::fmt::Debug + Any {
  7.  
  8. }
  9.  
  10. pub trait InsideType: std::fmt::Debug {}
  11.  
  12.  
  13. #[derive(Debug)]
  14. pub struct RealType(i32);
  15. impl InsideType for RealType { }
  16.  
  17.  
  18. #[derive(Debug)]
  19. pub struct ConcreteObject<T> where T: InsideType {
  20. field: T,
  21. }
  22.  
  23. impl<T> TypeErasedTrait for ConcreteObject<T> where T: InsideType + 'static {
  24.  
  25. }
  26.  
  27. #[derive(Debug)]
  28. pub struct Builder {
  29. objects: HashMap<i32, RefCell<Box<dyn TypeErasedTrait>>>,
  30. }
  31.  
  32. fn main() {
  33. let mut builder = Builder { objects: Default::default() };
  34. let obj = ConcreteObject { field: RealType(5) };
  35. builder.objects.insert(0, RefCell::new(Box::new( obj )) );
  36. {
  37. let ref_cell = builder.objects.get(&0).unwrap();
  38. let mut ref_mut = ref_cell.borrow_mut();
  39. let something = ref_mut.downcast_mut::<ConcreteObject<RealType>>().unwrap();
  40. println!("{:?}", something.field);
  41.  
  42.  
  43. }
  44.  
  45.  
  46. }
Add Comment
Please, Sign In to add comment