Sub topic 5
Writing Debug by hand
This chapter assumes you know how #[derive(Debug)] works and how {:?} and {:#?} print values. It also assumes you can write impl Trait for Type. Derive covers most types. Sometimes its output is wrong for your type, and then you implement Debug yourself.
When derive is not suitable
Derived Debug prints every field using that field's own Debug implementation. Three situations make that a poor fit:
- A field holds a secret, such as a password or token, that must not reach logs.
- A field does not implement
Debug, so derive fails to compile. - A field is huge or noisy, such as a buffer with thousands of bytes, and drowns the useful information.
The shape of a manual implementation
Debug has one required method, fmt. It receives a Formatter and returns fmt::Result. You could call write!(f, ...) directly, but the Formatter offers builder helpers that reproduce the standard output shape. Prefer the helpers. They handle commas, braces, and indentation for you.
| Helper | Output shape | Use for |
|---|---|---|
| `debug_struct` | `Name { a: 1, b: 2 }` | Structs with named fields |
| `debug_tuple` | `Name(1, 2)` | Tuple structs and tuple variants |
| `debug_list` | `[1, 2, 3]` | Sequence-like types |
| `debug_set` | `{1, 2, 3}` | Set-like types |
| `debug_map` | `{"a": 1, "b": 2}` | Map-like types |
Each builder ends with .finish(), which writes the closing delimiter and returns the fmt::Result for you to return.
Hiding a sensitive field
Here the password field is replaced with a placeholder, while the output keeps the familiar struct shape.
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 program prints:
Credentials { user: "ada", password: "<hidden>" }
Credentials {
user: "ada",
password: "<hidden>",
}Two details matter here:
.fieldtakes a&dyn Debug. Passing&"<hidden>"works because&strimplementsDebug, and it prints with quotes, as a real string field would.- The second
println!uses{:#?}, and you wrote no code for it. The builders check the formatter's alternate flag and switch to the multi-line layout themselves.
Leaving fields out with finish_non_exhaustive
If you omit fields, a reader of the log may assume the struct has no others. finish_non_exhaustive ends the output with .. to signal that something was skipped. It works on debug_struct builders.
use std::fmt;
struct Connection {
host: String,
socket_id: u32,
buffer: Vec<u8>,
}
impl fmt::Debug for Connection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Connection")
.field("host", &self.host)
.finish_non_exhaustive()
}
}
fn main() {
let c = Connection {
host: "db.local".to_string(),
socket_id: 7,
buffer: vec![0; 4096],
};
println!("{:?}", c);
println!("{:#?}", c);
println!("{} {}", c.socket_id, c.buffer.len());
}Output:
Connection { host: "db.local", .. }
Connection {
host: "db.local",
..
}The last line of main reads the skipped fields so the compiler does not warn that they are unused. In real code, those fields would be used elsewhere.
Tuple structs and collections
A newtype often needs a different representation than its derived form. A debug_tuple builder keeps the tuple look, and debug_list lets a wrapper print like the sequence it holds.
use std::fmt;
struct Meters(f64);
impl fmt::Debug for Meters {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Meters").field(&self.0).finish()
}
}
struct Stack {
items: Vec<i32>,
capacity_hint: usize,
}
impl fmt::Debug for Stack {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.items.iter()).finish()
}
}
fn main() {
println!("{:?}", Meters(3.5));
let s = Stack { items: vec![1, 2, 3], capacity_hint: 16 };
println!("{:?}", s);
println!("{:#?}", s);
println!("{}", s.capacity_hint);
}entries accepts any iterator whose items implement Debug. The Stack prints as [1, 2, 3], and with {:#?} each element goes on its own line. For maps, debug_map().entries(iter_of_pairs) works the same way, where each item is a (key, value) pair.
The write! shortcut and its cost
You can also write the output directly:
use std::fmt;
struct Token(String);
impl fmt::Debug for Token {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Token(<redacted>)")
}
}
fn main() {
let t = Token("abc123".to_string());
println!("{:?}", t);
println!("{:#?}", t);
println!("{}", t.0.len());
}This is fine for a one-line value like a token. The cost is that you now own the whole format. {:#?} prints the same single line, because write! knows nothing about the alternate flag. If the type has several fields, a manual write! on each field also gets you wrong indentation when the value is nested inside a larger pretty-printed structure. The builder helpers avoid that by wrapping the output in a writer that indents nested lines.
Gotchas
- Do not call
{:?}onselfinsidefmt.write!(f, "{:?}", self)recurses forever and overflows the stack. - Use
&self.field, notself.field..fieldtakes a reference. Passing a non-reference value moves it, or fails to compile. - Forgetting
.finish(). The builder is lazy about closing. Without.finish(), you get a compile error because the result is not returned, or you get truncated output. - Do not parse Debug output. The format is not stable between Rust versions and is meant for humans. Use
Displayor a serialization format when a program has to read the text. - Field names are strings you choose. The compiler will not catch a typo or a field you renamed later. Keep the names in sync with the struct.
Debugis not for users. Hiding a field is a developer-facing choice. Text shown to end users belongs inDisplay, covered next.
Exercise
A struct Session { id: u64, token: String, cache: Vec<u8> } should print Session { id: 42, .. } with {:?}, hiding token and cache. Which Formatter calls produce this, and what does {:#?} print?
Show answer
Use f.debug_struct("Session").field("id", &self.id).finish_non_exhaustive(). The {:?} output is Session { id: 42, .. }. With {:#?} the builder switches to the multi-line layout automatically: Session {, then id: 42,, then .., then }, each on its own line.
Exercise
Why does impl fmt::Debug for Node { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) } } fail at runtime, and how do you fix it?
Show answer
The {:?} inside fmt calls Debug::fmt on self again, which recurses until the stack overflows. Fix it by printing fields rather than self, for example with f.debug_struct("Node").field("value", &self.value).finish().