Pretty Print Struct in Rust

Pretty Print Struct in Rust

How to print structs and arrays? - how does one pretty print a rust struct or any data type?

Sure, one can write the custom Debug method. But is there some way which enables the print by default?

One option is to use:

5

1 Answer

When you implement Debug, Rust provides "pretty printing" with {:#?}. From the std::fmt documentation:

  • # - This flag indicates that the “alternate” form of printing should be used. The alternate forms are:
    • {:#?} - pretty-print the Debug formatting (adds linebreaks and indentation)
    • [others omitted]

Example:

#[derive(Debug)]
struct Person {
    name: &'static str,
    age: u8,
    hobbies: Vec<&'static str>,
}

fn main() {
    let peter = Person {
        name: "Jesse",
        age: 49,
        hobbies: vec!["crosswords", "sudoku"],
    };
    println!("{:#?}", peter);
}

Output:

Person {
    name: "Jesse",
    age: 49,
    hobbies: [
        "crosswords",
        "sudoku",
    ],
}

Playground

5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.