Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. #![allow(bad_style, unused)]#![warn(unused_must_use)]
  2.  
  3. use ::core::{any::Any, fmt::Debug};
  4.  
  5. trait Component : Any + Debug + 'static {
  6. fn upcast_Any_ref (self: &'_ Self)
  7. -> &'_ dyn Any
  8. ;
  9. fn upcast_Any_mut (self: &'_ mut Self)
  10. -> &'_ mut dyn Any
  11. ;
  12. fn upcast_Any_box (self: Box<Self>)
  13. -> Box<dyn Any>
  14. ;
  15. }
  16. impl<T : Any + Debug + 'static> Component for T {
  17. #[inline]
  18. fn upcast_Any_ref (self: &'_ Self)
  19. -> &'_ dyn Any
  20. {
  21. self
  22. }
  23.  
  24. #[inline]
  25. fn upcast_Any_mut (self: &'_ mut Self)
  26. -> &'_ mut dyn Any
  27. {
  28. self
  29. }
  30.  
  31. #[inline]
  32. fn upcast_Any_box (self: Box<Self>)
  33. -> Box<dyn Any>
  34. {
  35. self
  36. }
  37. }
  38.  
  39. impl dyn Component + 'static {
  40. #[inline]
  41. fn downcast_ref<T : 'static> (self: &'_ Self)
  42. -> Option<&'_ T>
  43. {
  44. self.upcast_Any_ref().downcast_ref::<T>()
  45. }
  46.  
  47. #[inline]
  48. fn downcast_mut<T : 'static> (self: &'_ mut Self)
  49. -> Option<&'_ mut T>
  50. {
  51. self.upcast_Any_mut().downcast_mut::<T>()
  52. }
  53. }
  54.  
  55. #[derive(Debug)]
  56. struct Foo {
  57. bar: u8
  58. }
  59.  
  60. fn main ()
  61. {
  62. let foo: Box<dyn Component> = Box::new(Foo { bar: 0 });
  63. let x = foo.downcast_ref::<Foo>();
  64.  
  65. println!("{:?}", foo);
  66. println!("{:?}", x);
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement