Advertisement
Guest User

Untitled

a guest
May 25th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.63 KB | None | 0 0
  1. use std::any::Any;
  2. use std::sync::Arc;
  3.  
  4. trait FooTrait: Any {
  5. fn method(&self) -> u32;
  6. }
  7.  
  8. struct Foo {
  9. value: u32,
  10. }
  11.  
  12. impl FooTrait for Foo {
  13. fn method(&self) -> u32 {
  14. self.value
  15. }
  16. }
  17.  
  18. fn new_foo() -> Option<Arc<FooTrait + Send + Sync + 'static>> {
  19. Some(Arc::new(Foo { value: 99 }))
  20. }
  21.  
  22. fn test(value: Arc<dyn Any + Send + Sync + 'static>) {
  23. if let Ok(s) = value.downcast::<Foo>() {
  24. println!("{}", s.method());
  25. }
  26. }
  27.  
  28. type Object = Arc<dyn Any + Send + Sync + 'static>;
  29.  
  30. fn main() {
  31. let cast: Option<Object> = new_foo().map(|c| {
  32. c.downcast::<>()
  33. });
  34.  
  35. test(cast);
  36. test(Arc::new(1));
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement