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.
#[derive(Debug)] struct User { id: u32, name: String } println!("{:?}", User { id: 1, name: "Ann".into() });
Try it
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.
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
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 samefmtmethod; the builders checkf.alternate()for you. Use the builder helpers instead ofwrite!so pretty printing keeps working.- Strings are quoted and escaped in Debug output (
"Ann \"A\""), andcharshows single quotes. This is a quick way to see hidden whitespace. - Derive requires
Debugon 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()andexpect()needE: Debugto build their panic message, which is why error types should implement it.
Related
Display,Clone,Default,std::error::Error- Lessons: Printing, Debugging, Display and From