Sub topic 7
Deriving Debug for Your Types
Prerequisites
This chapter assumes you can define structs and enums and run a program with cargo run. It also assumes you know that a trait is a set of methods a type can implement. You should have seen {:?} as the Debug placeholder in the previous chapter.
What the derive attribute does
println!("{:?}", value) only compiles if the type of value implements the Debug trait. Standard types such as integers, String, Vec<T> and Option<T> already do. Your own types do not, until you ask for it:
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{:?}", p);
}This prints Point { x: 1, y: 2 }.
#[derive(Debug)] is a procedural macro. The compiler runs it at compile time and generates an impl Debug for Point block for you. That generated code asks each field to format itself and wraps the results in the type name and braces.
flowchart LR
A["Type marked with derive Debug"] --> B["Compiler generates an impl of Debug"]
B --> C["Generated fmt writes the type name"]
C --> D["Each field is formatted by its own Debug impl"]
D --> E["Fields are joined into one string"]Every kind of struct and enum
Derive works on all the shapes of type you have seen so far. The output mirrors how you would write the value in source code.
#[derive(Debug)]
struct Meters(f64);
#[derive(Debug)]
struct Marker;
#[derive(Debug)]
enum Shape {
Circle { radius: f64 },
Rect(f64, f64),
Empty,
}
fn main() {
println!("{:?}", Meters(2.5));
println!("{:?}", Marker);
println!("{:?}", Shape::Circle { radius: 1.0 });
println!("{:?}", Shape::Rect(2.0, 3.0));
println!("{:?}", Shape::Empty);
}The output is:
Meters(2.5)
Marker
Circle { radius: 1.0 }
Rect(2.0, 3.0)
EmptyNotice three details:
- A tuple struct prints with parentheses and a named struct with braces and field names.
- A unit struct or unit variant prints as just its name.
- Enum variants print without the enum name. You see
Empty, notShape::Empty.
Every field must implement Debug
Derive does not make a type printable by itself. It only works if every field's type is also Debug. Suppose you write:
struct Engine {
cylinders: u8,
}
#[derive(Debug)]
struct Car {
engine: Engine,
}This fails to compile with error E0277: `Engine doesn't implement Debug `. The error points at the engine field inside Car, not at Engine itself. The fix is to derive Debug` on the inner type too:
#[derive(Debug)]
struct Engine {
cylinders: u8,
}
#[derive(Debug)]
struct Car {
engine: Engine,
}
fn main() {
let car = Car { engine: Engine { cylinders: 4 } };
println!("{:?}", car);
}This prints Car { engine: Engine { cylinders: 4 } }. Debug output nests, because each level calls the next level's own Debug implementation.
If the inner type comes from another crate and has no Debug, you cannot add a derive to it. In that case you write Debug for the outer type by hand. A later chapter shows how.
Generics and the added bound
When a type has generic parameters, derive adds a Debug requirement to each one. For this type:
#[derive(Debug)]
struct Pair<T> {
first: T,
second: T,
}
fn main() {
let a = Pair { first: 1, second: 2 };
let b = Pair { first: "x", second: "y" };
println!("{:?}", a);
println!("{:?}", b);
}the compiler generates roughly impl<T: Debug> Debug for Pair<T>. So Pair<i32> and Pair<&str> are printable, and Pair<Engine> would not be if Engine lacked Debug. The output is Pair { first: 1, second: 2 } and Pair { first: "x", second: "y" }.
The bound goes on every type parameter, even one that is never printed, such as a phantom marker. If you need Debug to work without that bound, write the implementation by hand.
Collections and strings
Standard containers print their contents using each element's Debug. Strings keep their quotes, which makes empty strings and stray whitespace visible.
#[derive(Debug)]
struct User {
name: String,
tags: Vec<String>,
manager: Option<String>,
}
fn main() {
let u = User {
name: "Ada".to_string(),
tags: vec!["admin".to_string(), "dev".to_string()],
manager: None,
};
println!("{:?}", u);
}This prints User { name: "Ada", tags: ["admin", "dev"], manager: None }.
Combining derives
Debug is usually derived together with other traits in one attribute:
#[derive(Debug, Clone, PartialEq)]
struct Id(u32);
fn main() {
let a = Id(7);
let b = a.clone();
println!("{:?} {:?} {}", a, b, a == b);
}This prints Id(7) Id(7) true. The order of names inside derive(...) does not matter.
Gotchas
| Situation | What happens | What to do |
|---|---|---|
| A field type lacks `Debug` | E0277 error on that field | Derive `Debug` on the field type, or implement `Debug` manually |
| Using `{}` on a derived type | Error: the type doesn't implement `Display` | Use `{:?}`, or implement `Display` yourself |
| Field is only ever printed | Compiler warns that the field is never read | Read the field somewhere, or silence the warning with `#[allow(dead_code)]` |
| Secret data in a field | Derived output prints it in full | Write a manual `Debug` that hides it |
Pretty printing
The same derive supports the multi-line {:#?} form with no extra code. The next chapter covers it in detail. The point to keep here is that you write the derive once and get both layouts.
Exercise
You derive Debug on struct Order { id: u32, customer: Customer }, but Customer has no derive. What does the compiler report, and what are two ways to fix it? Then say what println!("{:?}", Order { id: 3, customer: Customer { name: "Bo".to_string() } }) prints once it compiles, assuming Customer has the single field name: String.
Show answer
The compiler reports E0277, that Customer doesn't implement Debug, pointing at the customer field. Fix 1: add #[derive(Debug)] to Customer. Fix 2: implement Debug for Customer (or for Order) by hand, which is the choice when Customer is defined in another crate. After the fix, the output is Order { id: 3, customer: Customer { name: "Bo" } }.