Sub topic 16
Writing a custom Debug implementation
This chapter assumes you know how to derive Debug and how {:?} and {:#?} print values. It also assumes you have seen the Display implementation pattern with write! and a Formatter. Here you will write Debug by hand and learn when that is worth doing.
When derive is not enough
#[derive(Debug)] prints every field with its own Debug output. That is the right default, but it fails in a few cases:
- A field holds sensitive data, such as a password or token, that must not reach logs.
- A field's type does not implement
Debug, and you cannot change that type. - A field is huge, such as a 10 MB buffer, and printing it would flood the output.
- The internal layout is not the shape you want to show. A bit set stored as a
u8is better shown as the set of bit positions.
In each case you implement fmt::Debug yourself. The trait has one method, fmt, with the same signature as Display::fmt.
Using debug_struct
You could write Debug with write!, but the Formatter provides builder methods that match what derive generates. The builders handle commas, braces, indentation, and the {:#?} pretty layout for you.
use std::fmt;
#[allow(dead_code)]
struct Secret {
user: String,
password: String,
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Secret")
.field("user", &self.user)
.field("password", &"<hidden>")
.finish()
}
}
fn main() {
let s = Secret { user: "alice".to_string(), password: "hunter2".to_string() };
println!("{:?}", s);
println!("{:#?}", s);
}This prints:
Secret { user: "alice", password: "<hidden>" }
Secret {
user: "alice",
password: "<hidden>",
}The code never mentions {:#?}, yet the second line is pretty-printed. The builder reads the alternate flag from the Formatter and switches layout.
debug_struct takes the name to print. field takes a label and a reference to any value that implements Debug. finish writes the closing brace and returns the fmt::Result. Always call finish. Without it, the closing brace is never written and the result is not returned.
Fixing the quotes
The output above shows "<hidden>" with quotes, because &"<hidden>" is a &str and the Debug output of a string includes quotes. If you want a bare <hidden>, pass a small marker type whose Debug writes plain text:
use std::fmt;
struct Redacted;
impl fmt::Debug for Redacted {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("<hidden>")
}
}
#[allow(dead_code)]
struct Secret {
user: String,
password: String,
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Secret")
.field("user", &self.user)
.field("password", &Redacted)
.finish()
}
}
#[derive(Debug)]
struct Session {
id: u32,
creds: Secret,
}
fn main() {
let s = Session {
id: 1,
creds: Secret { user: "alice".to_string(), password: "hunter2".to_string() },
};
println!("{:?}", s);
}This prints Session { id: 1, creds: Secret { user: "alice", password: <hidden> } }. A derived Debug on Session calls your hand-written Debug on Secret, so the redaction applies everywhere the type is nested.
Hiding a field entirely
If a field should not appear at all, skip it and call finish_non_exhaustive instead of finish. It adds a .. marker to show that something was left out:
use std::fmt;
#[allow(dead_code)]
struct Secret {
user: String,
password: String,
}
impl fmt::Debug for Secret {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Secret")
.field("user", &self.user)
.finish_non_exhaustive()
}
}
fn main() {
let s = Secret { user: "alice".to_string(), password: "hunter2".to_string() };
println!("{:?}", s);
}The output is Secret { user: "alice", .. }. Which version you choose depends on whether a reader should know the field exists. finish_non_exhaustive has been stable since Rust 1.53.
The other builders
Each shape of data has its own builder:
| Method | Output shape | Typical use |
|---|---|---|
| `debug_struct(name)` | `Name { a: 1, b: 2 }` | Named fields |
| `debug_tuple(name)` | `Name(1, 2)` | Tuple structs |
| `debug_list()` | `[1, 2, 3]` | Ordered collections |
| `debug_set()` | `{1, 2, 3}` | Unordered unique items |
| `debug_map()` | `{"a": 1, "b": 2}` | Key-value collections |
The list, set, and map builders have an entries method that accepts an iterator. Here is a type that stores a set of flags in a u8 but prints the positions that are on:
use std::fmt;
struct Bits(u8);
impl fmt::Debug for Bits {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_set()
.entries((0..8u32).filter(|i| self.0 & (1u8 << *i) != 0))
.finish()
}
}
fn main() {
let b = Bits(0b0000_0101);
println!("{:?}", b);
println!("{:#?}", b);
}It prints {0, 2}, then the same two numbers on separate indented lines inside braces. For a map, entries takes an iterator of (key, value) pairs. You can also add items one at a time with entry on a set, list, or map builder.
Delegating to Display
Sometimes the right Debug output is already your Display output, for example a version number such as 1.4.2. Delegate by calling the other trait's method with the same formatter:
use std::fmt;
struct Version(u8, u8, u8);
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}.{}.{}", self.0, self.1, self.2)
}
}
impl fmt::Debug for Version {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
fn main() {
let v = Version(1, 4, 2);
println!("{:?} and {}", v, v);
println!("{:?}", vec![Version(0, 1, 0), Version(2, 0, 0)]);
}The second line prints [0.1.0, 2.0.0]. Passing f along keeps any width or fill the caller asked for, though this Display uses write! and so ignores them. Use f.pad if you want them honored.
Gotchas
- Debug is not a stable format. Do not parse it or compare it in tests that must survive refactors. The standard library may change its own
Debugoutput between releases. - Debug often ends up in logs. Panic messages,
unwrapfailures onResult<T, E>, and logging macros use{:?}. Redact inDebugeven if yourDisplayis already safe. - Do not build output by hand with
write!and braces unless you must. You lose{:#?}support and risk inconsistent layout. - Avoid recursion. Calling
{:?}onselfinside your ownfmtloops until the stack overflows. - Hand-written
Debugcan go stale. When you add a field, the compiler does not remind you to update the implementation. A derive picks it up automatically.
Exercise
A struct Token { owner: String, value: String } must print as Token { owner: "bob", .. } with {:?}, and the real value must never appear. Which Formatter methods do you call in the Debug implementation, and what does {:#?} print?
Show answer
Call f.debugstruct("Token").field("owner", &self.owner).finishnon_exhaustive(). The value field is not passed to the builder, so it cannot appear. With {:#?} the builder switches to the multi-line layout: Token {, then an indented owner: "bob", line, then an indented .. line, then }.
Exercise
You write impl fmt::Debug for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } }. What happens when you print a Point with {:?}, and why?
Show answer
It recurses forever and overflows the stack. The write! call formats self with {:?}, which calls Point's own Debug::fmt again. Format the fields instead, for example write!(f, "Point({}, {})", self.x, self.y), or use f.debug_struct.