Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. use std::{any::Any, fmt};
  2.  
  3. pub struct DebugAny {
  4. any: Box<dyn Any>,
  5. my_debug_impl: fn(&dyn Any, &mut fmt::Formatter) -> fmt::Result
  6. }
  7.  
  8.  
  9. impl DebugAny {
  10. pub fn from_debug<V: Any + fmt::Debug>(v: V) -> Self {
  11. // I'll just make the damn vtable *myself*!
  12. let my_debug_impl = |any: &dyn Any, f: &mut fmt::Formatter| {
  13. let v = any.downcast_ref::<V>().expect("debug vtable busted!");
  14. v.fmt(f)
  15. };
  16. Self {
  17. any: Box::new(v),
  18. my_debug_impl,
  19. }
  20. }
  21.  
  22. pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
  23. self.any.downcast_ref::<T>()
  24. }
  25. }
  26.  
  27. impl fmt::Debug for DebugAny {
  28. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  29. (self.my_debug_impl)(self.any.as_ref(), f)
  30. }
  31. }
  32.  
  33. fn main() {
  34. let foo = "I'm a string!";
  35. let any = DebugAny::from_debug(foo);
  36. println!("debug: {:?}", any);
  37. println!("downcast_ref: {:?}", any.downcast_ref::<&str>())
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement