The Debug Trait
Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 35 of 61.
Rust's standard library comes with many pre-defined traits that provide common functionality. One of the most useful for development is the Debug trait, which allows you to print a struct's contents for inspection.
If you try to print a custom struct directly, Rust won't know how to display it:
struct Player {
name: String,
score: u32,
}
let p = Player { name: String::from("Alice"), score: 100 };
println!("{:?}", p); // Error! Debug not implemented
The {:?} formatter requires the Debug trait. Instead of implementing it manually, Rust provides a shortcut—the #[derive] attribute. Place it directly above your struct definition:
#[derive(Debug)]
struct Player {
name: String,
score: u32,
}
let p = Player { name: String::from("Alice"), score: 100 };
println!("{:?}", p); // Player { name: "Alice", score: 100 }
The #[derive(Debug)] attribute tells the compiler to automatically generate the Debug implementation. This works as long as all fields in your struct also implement Debug (which most standard types do).
For more readable output with nested structures, use {:#?} for pretty-printing:
println!("{:#?}", p);
// Player {
// name: "Alice",
// score: 100,
// }
Deriving Debug is essential during development—it lets you quickly inspect your data without writing custom formatting code.
Challenge
EasyLet's make your structs inspectable by deriving the Debug trait! You'll create a simple inventory system where items can be printed for debugging purposes.
You'll organize your code across two files:
inventory.rs: Define a publicItemstruct with two public fields:name(String) andquantity(u32). Use the#[derive(Debug)]attribute to automatically implement the Debug trait for your struct.main.rs: Bring in your inventory module and create anIteminstance using the inputs provided. Print the item using the debug formatter{:?}to display its internal structure.
The beauty of deriving Debug is that Rust automatically generates the formatting code for you—no manual implementation needed! Your struct just needs the attribute, and it becomes printable with {:?}.
Your output should display the item in Rust's debug format:
Item { name: "{name}", quantity: {quantity} }For example, with inputs Keyboard and 15:
Item { name: "Keyboard", quantity: 15 }You will receive two inputs: the item name and the quantity (parse as u32).
Cheat sheet
The Debug trait allows you to print a struct's contents for inspection using the {:?} formatter.
Use the #[derive(Debug)] attribute to automatically implement Debug for your struct:
#[derive(Debug)]
struct Player {
name: String,
score: u32,
}
let p = Player { name: String::from("Alice"), score: 100 };
println!("{:?}", p); // Player { name: "Alice", score: 100 }
For pretty-printed output with better formatting, use {:#?}:
println!("{:#?}", p);
// Player {
// name: "Alice",
// score: 100,
// }
The #[derive(Debug)] attribute works as long as all fields in your struct also implement Debug, which most standard types do.
Try it yourself
mod inventory;
use inventory::Item;
fn main() {
// Read input
let mut name = String::new();
std::io::stdin().read_line(&mut name).expect("Failed to read line");
let name = name.trim().to_string();
let mut quantity_str = String::new();
std::io::stdin().read_line(&mut quantity_str).expect("Failed to read line");
let quantity: u32 = quantity_str.trim().parse().expect("Failed to parse quantity");
// TODO: Create an Item instance with the given name and quantity
// TODO: Print the item using the debug formatter {:?}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Methods and Behavior
Intro Implementation BlocksThe Self ParameterMutable MethodsAssociated FunctionsMultiple Implementation BlocksMethod ChainingRecap - Rectangle Actions4Project: Virtual Pet
Defining the PetFeeding the Pet7Standard Traits
The Debug TraitThe Display TraitClone and CopyEquality TraitsRecap - Printable Point10Project: Document System
The Draw TraitText Component2Encapsulation and Modules
Modules BasicsThe Public KeywordPrivate FieldsGettersSettersRecap - Secure Locker5Generics
Generic StructsGeneric MethodsMultiple Generic TypesGeneric FunctionsRecap - Coordinate Point8Traits as Bounds
Trait Bounds SyntaxMultiple BoundsThe Where ClauseReturning Types with TraitsRecap - Generic Printer11Design Patterns in Rust
Newtype PatternCompositionThe Drop TraitFrom and IntoRecap - Smart Pointer Mock