liveBook · Manning

Debug

As explained in Learn Rust in a Month of Lunches

Debug is the Rust trait for producing programmer-oriented representations of values.

Debug is a Rust trait for producing programmer-oriented representations of values. Use {:?} when ordinary Display formatting with {} is unavailable or too limited; use {:#?} for multiline pretty printing. section 1.8

Choose a formatter based on the output you need:

  • {} uses Display and usually produces prettier, more user-facing output. section 1.8
  • {:?} uses Debug and usually reveals more information on one line. section 1.8
  • {:#?} uses Debug with pretty printing, placing parts of a value on separate lines. section 1.8

Let the compiler suggest Debug

Printing the unit value () with {} produces an error because Display is not implemented. The compiler suggests {:?} or {:#?}; changing the formatter applies Debug instead. For custom types, #[derive(Debug)] usually supplies the implementation automatically, avoiding a hand-written fmt method. section 1.8 section 13.1.4

error[E0277]: `()` doesn't implement `std::fmt::Display`
 --> src\main.rs:3:41
  |
3 |     println!("This will not print: {}", doesnt_print);
  |                                         ^^^^^^^^^^^^ `()` 
  cannot be formatted with the default formatter
  |
  = help: the trait `std::fmt::Display` is not implemented for `()`
  = note: in format strings you may be able to use `{:?}` (or {:#?} 
  for pretty-print) instead
  = note: required by `std::fmt::Display::fmt`

Inspect the compiler diagnostic that explains why {} fails for () and recommends Debug formatting. section 1.8

User {
    name: "Mr. User",
    user_number: 101,
}

Compare compact and pretty Debug output for a User value. section 1.8

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains format choices, compiler guidance, pretty output, and derive(Debug), but defers manual fmt implementation.
Examples
Uses the unit value (), compiler error E0277, and a User structure to contrast ordinary and pretty Debug output.
What it assumes
Builds trait vocabulary from the idea that a trait describes what a type can do.
What you can do after
Apply Debug via println! using {:?}, {:#?}, and #[derive(Debug)] to inspect values.
How it connects
Connects Debug with Display, traits, println!, format strings, and automatic trait derivation.

Also explained in

Compare how 2 books explain Debug →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.