SHARE
TWEET

Untitled

a guest Oct 23rd, 2019 75 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use std::rc::Rc;
  2. use std::any::Any;
  3.  
  4. trait Avatar: Any {
  5.     fn draw(&self);
  6.    
  7.     fn as_any(self: Rc<Self>) -> Rc<dyn Any>;
  8. }
  9.  
  10. struct PointAvatar {
  11.     x: i32,
  12.     y: i32,
  13. }
  14.  
  15. impl Avatar for PointAvatar {
  16.     fn draw(&self) {}
  17.    
  18.     fn as_any(self: Rc<Self>) -> Rc<dyn Any> {
  19.         self
  20.     }
  21. }
  22.  
  23. struct APIData {
  24.     root: Rc<dyn Avatar>,
  25. }
  26.  
  27. fn init_api(avatar: Rc<dyn Avatar>) -> APIData {
  28.     APIData {root: avatar}
  29. }
  30.  
  31. fn api_draw(api: &APIData) {
  32.     api.root.draw();
  33. }
  34.  
  35. fn main() {
  36.     let avatar: Rc<dyn Avatar> = Rc::new(PointAvatar {x: 0, y: 0});
  37.     let api = init_api(Rc::clone(&avatar));
  38.    
  39.     // these two lines would happen every frame or something
  40.     let avatar = avatar.as_any().downcast::<PointAvatar>().unwrap();
  41.     avatar.x += 1;
  42.    
  43.     api_draw(&api);
  44. }
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