Sub topic 7
Deriving Debug for your types
This chapter assumes you know basic Rust syntax, how to define structs and enums, and that a trait is a set of behavior a type can implement. Earlier chapters covered {} and Display. Here you will learn how #[derive(Debug)] gives your own types {:?} output.
Why Debug is separate from Display
Display is for text shown to users, so Rust never guesses its layout. You write it yourself. Debug is for programmers, and its layout is mechanical, so the compiler can generate it for you.
Without Debug, a custom type cannot be used with {:?}.
Adding the derive
Put #[derive(Debug)] above a struct or enum. The compiler writes the Debug implementation from the type's fields.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug)]
enum Shape {
Dot,
Circle(f64),
Rect { w: u32, h: u32 },
}
fn main() {
let p = Point { x: 1, y: 2 };
println!("{:?}", p);
println!("{:?}", Shape::Dot);
println!("{:?}", Shape::Circle(1.5));
println!("{:?}", Shape::Rect { w: 3, h: 4 });
}This prints:
Point { x: 1, y: 2 }
Dot
Circle(1.5)
Rect { w: 3, h: 4 }The output follows the shape of the definition. Named fields appear as name: value, tuple variants use parentheses, and unit variants print only their name.
Every field must implement Debug
A derive works only if every field's type also implements Debug. Standard types such as integers, String, Vec<T>, and Option<T> already do. For generic containers, the element type must implement it too.
#[derive(Debug)]
struct Inner {
id: u8,
}
#[derive(Debug)]
struct Outer {
name: String,
inner: Inner,
tags: Vec<&'static str>,
parent: Option<u8>,
}
fn main() {
let o = Outer {
name: "demo".to_string(),
inner: Inner { id: 9 },
tags: vec!["a", "b"],
parent: None,
};
println!("{:?}", o);
}If you remove the derive from Inner, the program no longer compiles. The error says that Inner doesn't implement Debug, and the fix is to add the derive to Inner.
How Debug shows values
Debug output is designed to be unambiguous. Strings keep their quotes and escapes, so you can tell "5" from 5.
fn main() {
println!("{}", "a\"b");
println!("{:?}", "a\"b");
println!("{:?}", 'x');
println!("{:?}", Some("hi"));
}This prints a"b, then "a\"b", then 'x', then Some("hi").
Pretty output is the next step
{:?} puts everything on one line. That is hard to read for nested data. The {:#?} form spreads the same output over several indented lines. The next chapter covers it.
Exercise
You define struct Config { path: String, retries: u32 } and call println!("{:?}", cfg). The compiler reports that Config doesn't implement Debug. What is the smallest change that fixes it, and what will the output look like for path = "a.txt" and retries = 3?
Show answer
Add #[derive(Debug)] above the struct. The output is Config { path: "a.txt", retries: 3 }. The string keeps its quotes because Debug output marks values unambiguously.
Exercise
A struct Account has a field token: String. You derive Debug and log the struct. What is the risk?
Show answer
Derived Debug prints every field, so the token appears in the log in plain text. Implement Debug manually and hide or leave out that field.