Sub topic 5
Writing Debug by Hand
This chapter assumes you know how #[derive(Debug)] works, how impl Trait for Type is written, and how println! format strings behave. Here you will write Debug yourself and see when that is worth doing.
When derive is not suitable
#[derive(Debug)] prints every field. That is a problem in three cases:
- A field holds a secret, such as a password or token. Logs and panic messages would leak it.
- A field is huge or noisy, such as a buffer with thousands of bytes.
- A field's type does not implement
Debug, so derive fails to compile.
In these cases you implement fmt::Debug yourself.
The Formatter helper methods
Debug::fmt receives a &mut fmt::Formatter. You could write text into it with write!, but then {:#?} would no longer produce the indented layout. The Formatter has helper methods that handle both layouts for you:
| Method | Use for |
|---|---|
| `debug_struct("Name")` | Structs with named fields |
| `debug_tuple("Name")` | Tuple structs and tuple variants |
| `debug_list()` | Sequences |
| `debug_map()` | Key-value pairs |
Each returns a builder. You add fields, then call .finish().
Example: hiding a password
use std::fmt;
struct Credentials {
user: String,
password: String,
}
impl fmt::Debug for Credentials {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Credentials")
.field("user", &self.user)
.field("password", &"<hidden>")
.finish()
}
}
fn main() {
let c = Credentials {
user: "ada".to_string(),
password: "hunter2".to_string(),
};
println!("{:?}", c);
println!("{:#?}", c);
}The first line prints Credentials { user: "ada", password: "<hidden>" }. The second prints the same data over several lines. You wrote no code for the second layout. The builder switched to it because of the # flag.
The .field method takes &dyn Debug. The string "<hidden>" is formatted with Debug, so it appears in quotes. That is fine for a placeholder.
Skipping fields
If you leave fields out, say so. Call .finish_non_exhaustive() instead of .finish(). It adds .. to the output, which tells the reader that something was omitted.
use std::fmt;
struct Session {
id: u32,
token: String,
}
impl fmt::Debug for Session {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Session")
.field("id", &self.id)
.finish_non_exhaustive()
}
}
fn main() {
let s = Session { id: 7, token: "abc".to_string() };
println!("{:?}", s);
let _ = &s.token;
}This prints Session { id: 7, .. }.
Common mistakes
- Using
write!for a struct. It compiles, but{:#?}loses its pretty layout. - Forgetting
.finish(). The builder does nothing until you call it, and the compiler warns that the result is unused. - Hand-writing
Debugwhen derive would do. A manual version does not update when you add a field, so it can silently go stale.
Exercise
A struct ApiClient has the fields endpoint: String and api_key: String. Write a Debug implementation that prints the endpoint but shows api_key as "<redacted>". Which builder method do you start with, and which one ends the chain?
Show answer
Start with f.debug_struct("ApiClient"), then add .field("endpoint", &self.endpoint) and .field("api_key", &"<redacted>"), and end with .finish(). The full body is f.debug_struct("ApiClient").field("endpoint", &self.endpoint).field("api_key", &"<redacted>").finish().
Exercise
Why is debug_struct preferred over write!(f, "Credentials {{ user: {} }}", self.user) inside a Debug implementation?
Show answer
debug_struct handles both the compact {:?} and the pretty {:#?} layouts, and it formats each field with Debug. A plain write! produces one fixed layout, so {:#?} would not be indented.