SHARE
TWEET

Untitled

a guest Aug 22nd, 2019 85 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top