15

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: https://docs.rs/pretty-trait/latest/pretty_trait/

Coder
  • 1,415
  • 2
  • 23
  • 49
  • 3
    What's wrong with the answer in the linked question? "Using `#[derive(Debug)]` is the easiest solution." – John Kugelman Jun 15 '22 at 20:02
  • It is default print and not pretty print. – Coder Jun 15 '22 at 20:03
  • No, I don't mean to self answer. But I am looking for a different way without using any other trait (is possible). – Coder Jun 15 '22 at 20:04
  • 2
    according to [one of the comments on your linked post](https://stackoverflow.com/questions/30253422/how-to-print-structs-and-arrays#comment97289268_30253540), you can use `{:#?}` for moderately prettier formatting of the `Debug` trait – Jeremy Meadows Jun 15 '22 at 20:10
  • _"is there some way which enables the print by default?"_ -- No, that's exactly what `Debug` is for in the first place. – cdhowie Jun 15 '22 at 20:14

1 Answers1

33

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thanks. This is useful. Any idea why this is not the default format option? – Coder Jun 15 '22 at 21:35
  • 8
    People often want to print debugging info in log messages, which works best when it's all on one line. – John Kugelman Jun 15 '22 at 21:45
  • @VikasGoel It's very verbose. I do all my debugging via log statements. If the `Vec`s that I print out are all pretty-printed, I would be wading through several hundreds of lines of output rather than less than one page. – lmat - Reinstate Monica Jan 26 '23 at 02:51
  • Doesn't this not work when usiing third-party creates, unless you change their code?v Third-party crates are often the source of difficulty. Would be great if this was easier. – JohnAllen Feb 10 '23 at 09:16
  • It works with third-party crates. – John Kugelman Feb 10 '23 at 15:01