Debug

All types which want to use std::fmt formatting traits require an
implementation to be printable. Automatic implementations are only provided
for types such as in the std library. All others must be manually
implemented somehow.

The fmt::Debug trait makes this very straightforward. All types can
derive (automatically create) the fmt::Debug implementation. This is
not true for fmt::Display which must be manually implemented.

  1. // This structure cannot be printed either with `fmt::Display` or
  2. // with `fmt::Debug`
  3. struct UnPrintable(i32);
  4. // The `derive` attribute automatically creates the implementation
  5. // required to make this `struct` printable with `fmt::Debug`.
  6. #[derive(Debug)]
  7. struct DebugPrintable(i32);

All std library types automatically are printable with {:?} too:

  1. // Derive the `fmt::Debug` implementation for `Structure`. `Structure`
  2. // is a structure which contains a single `i32`.
  3. #[derive(Debug)]
  4. struct Structure(i32);
  5. // Put a `Structure` inside of the structure `Deep`. Make it printable
  6. // also.
  7. #[derive(Debug)]
  8. struct Deep(Structure);
  9. fn main() {
  10. // Printing with `{:?}` is similar to with `{}`.
  11. println!("{:?} months in a year.", 12);
  12. println!("{1:?} {0:?} is the {actor:?} name.",
  13. "Slater",
  14. "Christian",
  15. actor="actor's");
  16. // `Structure` is printable!
  17. println!("Now {:?} will print!", Structure(3));
  18. // The problem with `derive` is there is no control over how
  19. // the results look. What if I want this to just show a `7`?
  20. println!("Now {:?} will print!", Deep(Structure(7)));
  21. }

So fmt::Debug definitely makes this printable but sacrifices some
elegance. Rust also provides “pretty printing” with {:#?}.

  1. #[derive(Debug)]
  2. struct Person<'a> {
  3. name: &'a str,
  4. age: u8
  5. }
  6. fn main() {
  7. let name = "Peter";
  8. let age = 27;
  9. let peter = Person { name, age };
  10. // Pretty print
  11. println!("{:#?}", peter);
  12. }

One can manually implement fmt::Display to control the display.

See also

attributes, derive, std::fmt,
and struct