Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Core Traits

The Debug trait

Reference for the Rust Debug trait: derive it, print with {:?} and {:#?}, write a manual impl with the debug_* helpers, and know its limits.

std::fmt::Debug is the trait behind the {:?} and {:#?} format specifiers. It produces a programmer-oriented description of a value, meant for logs, dbg!, test failures and panic messages, not for end users (that is the job of Display).

Almost every type gets it with #[derive(Debug)]. Standard types such as integers, strings, Vec<T>, Option<T> and HashMap<K, V> already implement it, as long as their contents do.

Rust
#[derive(Debug)]
struct User { id: u32, name: String }
println!("{:?}", User { id: 1, name: "Ann".into() });

Try it

Rust Derive, compact and pretty output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust A manual implementation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub trait Debug {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
}
Name Description
&self The value to describe.
f The formatter. It carries flags such as # (pretty) and width, and offers debug_struct, debug_tuple, debug_list, debug_set, debug_map.

Returns: fmt::Result, that is Result<(), fmt::Error>. Return the error from write! with ? and never create one yourself.

Usage notes

  • {:?} is one line, {:#?} is multi-line and indented. Both come from the same fmt method; the builders check f.alternate() for you. Use the builder helpers instead of write! so pretty printing keeps working.
  • Strings are quoted and escaped in Debug output ("Ann \"A\""), and char shows single quotes. This is a quick way to see hidden whitespace.
  • Derive requires Debug on every field. Add a manual impl for a field type that lacks it, or wrap it.
  • The format is not stable. Do not parse Debug output or compare it in production logic. Tests that compare exact text break across compiler versions for some types.
  • Hide secrets by hand. A derived impl prints every field, including passwords and tokens. Write a manual impl as shown above.
  • Hex flags: {:x?} and {:X?} print integers inside collections in hex; {:02x?} also pads.
  • dbg! prints file, line, the expression and its Debug value to stderr, then returns the value, so it can wrap any expression.
  • unwrap() and expect() need E: Debug to build their panic message, which is why error types should implement it.