Sub topic 3
Debug: printing values for developers
This chapter covers the Debug trait: what it promises, how #[derive(Debug)] satisfies it, where it is used in everyday Rust, and how it can fail to compile or leak data. It assumes you can read basic structs, enums, and generics, and that you know println! format strings.
What Debug is for
Debug is the standard library's trait for showing a value to the programmer. Its output is meant for logs, test failures, and quick inspection. It is not meant for end users. The trait lives in std::fmt and has one required method, fmt. You rarely write that method yourself, because the compiler can generate it.
The format placeholder {:?} calls Debug. Any type that implements Debug can be printed with it. That includes most standard types: integers, String, Vec<T>, Option<T>, tuples, and references to them, as long as their contents are also Debug.
Deriving Debug
The derive attribute asks the compiler to write the trait implementation for you. For Debug, the generated code prints the type name and then each field. It does this recursively through nested values.
#[derive(Debug)]
enum Shape {
Circle { radius: f64 },
Rect(f64, f64),
Empty,
}
#[derive(Debug)]
struct Drawing {
name: String,
shapes: Vec<Shape>,
origin: Option<(i32, i32)>,
}
fn main() {
let d = Drawing {
name: "demo".to_string(),
shapes: vec![Shape::Circle { radius: 1.5 }, Shape::Rect(2.0, 3.0), Shape::Empty],
origin: Some((0, 0)),
};
println!("{:?}", d);
}This prints:
Drawing { name: "demo", shapes: [Circle { radius: 1.5 }, Rect(2.0, 3.0), Empty], origin: Some((0, 0)) }Notice how the output mirrors the Rust syntax you would write to build the value. Named-field structs use braces, tuple variants use parentheses, and unit variants are just their name.
The all-fields rule
A derived Debug only compiles if every field's type also implements Debug. If a struct contains a field of a type without Debug, the compiler reports that the trait bound is not satisfied and points at the field. There are two fixes. Add #[derive(Debug)] to the field's type if you own it, or implement Debug by hand for the outer type and skip or replace that field. A later chapter covers the manual route.
Generics follow the same rule. For struct Pair<T> { a: T, b: T }, derive generates impl<T: Debug> Debug for Pair<T>. So a Pair<i32> is printable, but a Pair<SomethingWithoutDebug> is not.
Trait objects need a small extra step. A field of type Box<dyn Component> is only Debug if the trait itself requires it:
use std::fmt::Debug;
trait Component: Debug {
fn name(&self) -> &str;
}
#[derive(Debug)]
struct Button {
label: String,
}
impl Component for Button {
fn name(&self) -> &str {
&self.label
}
}
#[derive(Debug)]
struct Window {
parts: Vec<Box<dyn Component>>,
}
fn main() {
let w = Window {
parts: vec![Box::new(Button { label: "OK".to_string() })],
};
println!("{:?} / {}", w, w.parts[0].name());
}Here trait Component: Debug makes Debug a supertrait. Every implementor must be Debug, so dyn Component is Debug too, and Window can derive it.
Where Debug shows up
You use Debug more often than you may realize, because many standard tools require it.
unwrap()on aResult<T, E>requiresE: Debug, because the panic message prints the error.expect()has the same requirement onE.assert_eq!(a, b)andassert_ne!require both sides to beDebug, so a failed test can show both values.maincan returnResult<(), E>whenE: Debug. On error, the runtime printsError:followed by theDebugoutput.dbg!prints an expression, its value, and its source location to standard error, then returns the value.
A function that accepts any printable value uses a Debug bound:
use std::fmt::Debug;
fn show_all<T: Debug>(items: &[T]) {
for (i, item) in items.iter().enumerate() {
println!("{i}: {item:?}");
}
}
fn main() {
show_all(&["a", "b"]);
show_all(&[Some(1), None]);
let total = dbg!(2 * 3) + 1;
println!("{total}");
}The dbg! call writes a line like [src/main.rs:12:17] 2 * 3 = 6 to standard error. Because dbg! returns its argument, you can wrap it around part of an expression without changing the program's result.
Debug versus Display
Debug and Display look similar but have different jobs.
| Aspect | Debug (`{:?}`) | Display (`{}`) |
|---|---|---|
| Audience | Developers | End users |
| Derivable | Yes | No, must be written by hand |
| Implemented by most std types | Yes | Only for types with an obvious text form |
| Strings | Quoted and escaped: `"hi\n"` | Raw text |
| Floats | `2.0` | `2` |
| Format stability | Not guaranteed | Defined by your code |
The string row has a practical use. println!("{:?}", "a\"b") prints "a\"b", so invisible characters such as newlines and tabs become visible. That makes Debug the better choice when you are hunting for stray whitespace in input.
Gotchas
The format is not a contract. The exact text from derived Debug can change between compiler versions. Do not parse it, compare it in tests, or send it over a network. If other code needs to read the output, define a real format with Display or a serialization library.
Derive prints everything. Derived Debug includes every field, including passwords, tokens, and personal data. If a struct is logged with {:?}, those values end up in your logs. For types holding secrets, write Debug by hand and mask the sensitive fields.
Derive is all or nothing. You cannot ask derive to skip one field. You either accept every field or write the implementation yourself.
Debug on Rc and RefCell. Rc<T> prints its inner value. RefCell<T> prints RefCell { value: .. } when it can borrow, and a placeholder when it is already mutably borrowed. Printing does not panic, but it may not show what you expect during a mutable borrow.
Choosing derive or manual
Derive Debug by default. It costs one line, stays correct when you add fields, and is what most Rust code does. Write it by hand when a field must be hidden, when a field's type cannot implement Debug, or when the raw layout would be unreadable. The next two chapters cover the two output layouts, {:?} and {:#?}, and then the manual route.
Exercise
A struct Config contains a field handle: NativeHandle, where NativeHandle is defined in your own crate and has no derives. You add #[derive(Debug)] to Config, and compilation fails. Give two ways to fix this, and name one reason to prefer the second.
Show answer
First, add #[derive(Debug)] to NativeHandle, since you own it. Second, implement Debug for Config by hand and either skip handle or print a placeholder for it. The second is better when the handle's contents are sensitive or meaningless in a log, because derive cannot omit or mask a single field.
Exercise
What does println!("{:?}", Some("hi")) print, and how does it differ from what {} would do with the same value?
Show answer
It prints Some("hi"), with the quotes included. {} would not compile, because Option<&str> does not implement Display.