The Debug Trait
Debug trait teaches a struct how to print itself out in a readable way when you're just trying to peek inside it.Deriving Debug
Adding #[derive(Debug)] above a struct definition automatically generates an implementation that lets you print the struct's fields for debugging purposes.
Example: Deriving Debug
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 3, y: 7 };
println!("{:?}", p);
}
Login to try C/C++/Java/PHP code in the editor
Pretty-Printing with {:#?}
The alternate format specifier {:#?} prints a Debug value across multiple lines with indentation, making it easier to read for structs with many fields.
Example: Pretty-Printing with {:#?}
#[derive(Debug)]
struct User {
name: String,
age: u32,
}
fn main() {
let user = User { name: String::from("Grace"), age: 40 };
println!("{:#?}", user);
}
Login to try C/C++/Java/PHP code in the editor
Debug on Nested Structs
Debug derives recursively: if a struct contains another struct as a field, that inner struct must also derive Debug for the whole thing to be printable.
Example: Debug on Nested Structs
#[derive(Debug)]
struct Address {
city: String,
}
#[derive(Debug)]
struct Person {
name: String,
address: Address,
}
fn main() {
let p = Person { name: String::from("Sam"), address: Address { city: String::from("Oslo") } };
println!("{:?}", p);
}
Login to try C/C++/Java/PHP code in the editor
Debug vs Display
Debug ({:?}) is meant for developer-facing diagnostic output and can be auto-derived, while Display ({}) is meant for polished, user-facing text and must be implemented manually.
Example: Debug vs Display
#[derive(Debug)]
struct Item {
name: String,
price: f64,
}
fn main() {
let item = Item { name: String::from("Widget"), price: 9.99 };
println!("Debug view: {:?}", item);
}
Login to try C/C++/Java/PHP code in the editor
- Trying to print a struct with
{}when it only implementsDebug, notDisplay-- these use different placeholder syntax. - Forgetting to add
#[derive(Debug)]above a struct, then getting a compile error that the type doesn't implementDebug. - Not knowing about the pretty-print placeholder
{:#?}for nicely indented, multi-line struct output.
#[derive(Debug)]automatically implements theDebugtrait for a struct.{:?}is the format placeholder used to print a value that implementsDebug.{:#?}produces a nicely indented, multi-line pretty-print version of the same output.Debugoutput is meant for developers debugging their code, not for polished user-facing text.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: