← Back to Rust Course | Chapter 7: Structs | Lesson 5 of 7

The Debug Trait

The 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

markup
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 3, y: 7 };
    println!("{:?}", p);
}

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 {:#?}

markup
#[derive(Debug)]
struct User {
    name: String,
    age: u32,
}

fn main() {
    let user = User { name: String::from("Grace"), age: 40 };
    println!("{:#?}", user);
}

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

markup
#[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);
}

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

markup
#[derive(Debug)]
struct Item {
    name: String,
    price: f64,
}

fn main() {
    let item = Item { name: String::from("Widget"), price: 9.99 };
    println!("Debug view: {:?}", item);
}
Common Mistakes
  1. Trying to print a struct with {} when it only implements Debug, not Display -- these use different placeholder syntax.
  2. Forgetting to add #[derive(Debug)] above a struct, then getting a compile error that the type doesn't implement Debug.
  3. Not knowing about the pretty-print placeholder {:#?} for nicely indented, multi-line struct output.
Chapter Summary
  • #[derive(Debug)] automatically implements the Debug trait for a struct.
  • {:?} is the format placeholder used to print a value that implements Debug.
  • {:#?} produces a nicely indented, multi-line pretty-print version of the same output.
  • Debug output 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.