Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. use std::fmt;
  2.  
  3. /// Extends a (possibly unsized) value with a Debug string.
  4. // (This type is unsized when T is unsized)
  5. pub struct Debuggable<T: ?Sized> {
  6. text: &'static str,
  7. value: T,
  8. }
  9.  
  10. /// Produce a Debuggable<T> from an expression for T
  11. macro_rules! dbg {
  12. ($($body:tt)+) => {
  13. Debuggable {
  14. text: stringify!($($body)+),
  15. value: $($body)+,
  16. }
  17. };
  18. }
  19.  
  20. impl<T: ?Sized> fmt::Debug for Debuggable<T> {
  21. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  22. write!(f, "{}", self.text)
  23. }
  24. }
  25.  
  26. // This makes Debuggable have most methods of the thing it wraps.
  27. // It also lets you call it when T is a function.
  28. impl<T: ?Sized> ::std::ops::Deref for Debuggable<T> {
  29. type Target = T;
  30. fn deref(&self) -> &T {
  31. &self.value
  32. }
  33. }
  34.  
  35. fn main() {
  36. let d = &dbg!(|x| {
  37. let _ = "random code so you can see how it's formatted";
  38. assert_eq!(3 * (1 + 2), 9);
  39. x * x
  40. });
  41. println!("{:?}", d);
  42. println!("{}", d(100));
  43.  
  44. let f = 100;
  45. let e = dbg!(100 + f);
  46. println!("{:?} = {}", e, *e);
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement