How to Make a Struct Printable with Debug and Display

Derive Debug for quick debugging output and implement Display for custom user-friendly formatting.

Derive the Debug and Display traits for your struct to enable printing with {:?} and {} respectively.

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl std::fmt::Display for Rectangle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Rectangle({}, {})", self.width, self.height)
    }
}

fn main() {
    let rect = Rectangle { width: 30, height: 50 };
    println!("Debug: {:?}", rect);
    println!("Display: {}", rect);
}