Sub topic 16
Writing a custom Debug implementation
This chapter assumes you can derive Debug with #[derive(Debug)], you know what a trait is, and you have already implemented Display for a type. Here you will write Debug by hand and learn when that is worth doing.
Why replace the derived version
The derive prints every field exactly as it is. That is usually what you want, but sometimes it is not:
- A field holds a secret, such as a password or token, that must stay out of logs.
- A field is huge, such as a buffer with thousands of bytes, and drowns the useful output.
- The internal layout is not what a reader needs to see.
In these cases you implement fmt::Debug yourself. The method has the same shape as Display::fmt.
Using debug_struct
You could build the text with write!. A better choice is the helper methods on Formatter, starting with debug_struct. They produce the same layout the derive would, and they handle {:#?} for you.
use std::fmt;
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);
}The first line prints Secret { user: "alice", password: "<hidden>" }. The second prints the same data over several indented lines, with no extra code from you.
Each call has a job:
debug_struct("Secret")starts the output with the type name..field(name, &value)adds one field. The value only needs to implementDebug..finish()closes the output and returns thefmt::Result.
The placeholder &"<hidden>" is a &str, and Debug for strings keeps the quotes. That is why the output shows "<hidden>" in quotes.
Other builders
Formatter has a builder for each common shape:
| Method | Output style |
|---|---|
| `debug_struct` | `Name { a: 1, b: 2 }` |
| `debug_tuple` | `Name(1, 2)` |
| `debug_list` | `[1, 2, 3]` |
| `debug_map` | `{"k": 1}` |
| `debug_set` | `{1, 2}` |
If you leave fields out on purpose, call .finish_non_exhaustive() instead of .finish(). It adds .. to show that something was omitted.
Common errors
- Using
write!for a struct. It compiles, but{:#?}then prints one flat line, because you built the text yourself. Use the builders. - Calling
.fieldwithout.finish(). The builder does nothing useful until you finish it. The compiler warns that the value is unused. - Printing the real secret in a nested type. If another struct has a
Secretfield and derivesDebug, it calls your implementation. That is the benefit of the trait. Check that no otherDebugpath prints the raw data.
Exercise
A type prints correctly with {:?} but {:#?} shows everything on one line. Its Debug implementation uses write!. How do you fix it?
Show answer
Replace the write! call with debugstruct (or debugtuple, debug_list, and so on), add each field with .field, and end with .finish(). The builders check whether the alternate flag is set and produce indented multi-line output when it is.