Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. use std::collections::HashMap;
  2. use std::rc::Rc;
  3. use std::any::Any;
  4.  
  5. trait Attribute: AsAny {
  6. fn memory_size(&self) -> u32 { 42 }
  7. }
  8.  
  9. impl Attribute for (f32, f32) {}
  10. impl Attribute for u32 {}
  11.  
  12. fn main() {
  13. let mut h = HashMap::<String, Rc<dyn Attribute>>::new();
  14.  
  15. h.insert("foo".into(), Rc::new((22.0, 22.0)));
  16. h.insert("bar".into(), Rc::new(42));
  17.  
  18. let size = h.values()
  19. .map(|rc| rc.memory_size())
  20. .sum::<u32>();
  21.  
  22. if let Ok(attr) = h.get_mut("foo").unwrap()
  23. .clone().into_any_rc()
  24. .downcast::<(f32, f32)>()
  25. {
  26. dbg!(attr);
  27. }
  28. }
  29.  
  30.  
  31. trait AsAny {
  32. fn into_any_rc(self: Rc<Self>) -> Rc<dyn Any>;
  33. }
  34.  
  35. impl<T: Any> AsAny for T {
  36. fn into_any_rc(self: Rc<Self>) -> Rc<dyn Any> {
  37. self
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement