liveBook · Manning

Debug

As explained in Refactoring to Rust

The Debug trait is a Rust formatting trait for producing developer-oriented representations of values.

Debug is a Rust formatting trait that produces developer-oriented representations of values. It is especially useful when an error must be displayed during a panic. section 2.5.6

Use Debug to support concise error handling:

  • Derive Debug on an error enum so the compiler generates a printable representation. section 2.5.6
  • Call unwrap() or expect() on a Result only when its error type implements Debug. section 2.5.6
  • Use Debug output to reveal values such as enum variants, hidden escape codes, or data-structure internals. section 2.5.6 section 3.3

Making an error printable

Add #[derive(Debug)] to the error type, then unwrap() can report the failing value: thread 'main' panicked at 'called Result::unwrap() on an Err value: GotNegative'. section 2.5.6

#[derive(Debug)]
enum Error {
  GotNegative,
}

See the minimal derive annotation that enables developer-oriented formatting for an error enum. section 2.5.6

How Refactoring to Rust covers it

How deep it goes
Defines developer representation and demonstrates enum derivation, but defers deeper trait details.
Examples
Uses a FizzBuzz Error enum with GotNegative, #[derive(Debug)], unwrap(), expect(), and panic output.
What it assumes
Assumes Result-based error handling and introduces Debug as a prerequisite for simplified panic handling.
What you can do after
Apply it via #[derive(Debug)] so Rust errors can be printed by unwrap() and expect().
How it connects
Connects derive attributes, enums, Result, unwrap(), expect(), panic handling, and Display formatting.

Also explained in

Compare how 2 books explain Debug →

Related concepts

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