Skip to content

Print structs and arrays in Rust

For a struct you own, the usual way to print its fields for debugging is to derive Debug and use {:?}. With captured identifiers, write println!("{value:?}"). Use {:#?} for the pretty multi-line form.

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/print_values_pages.rs#debug-print-struct
#[derive(Debug)]
struct User {
    name: &'static str,
    active: bool,
}

let user = User {
    name: "Ada",
    active: true,
};

println!("{user:?}");
println!("{user:#?}");

The checked test verifies that the generated Debug representation contains the struct and field information, without treating its exact textual layout as a stable format.

#[derive(Debug)] asks Rust to generate the Debug implementation from the fields of your struct. This works when the fields themselves support Debug.

If the compiler says your type does not implement Debug, see E0277: type doesn’t implement Debug.

If the derived representation includes fields you do not want in diagnostic output, implement custom Debug instead of adding post-processing around the formatted string.

Use {:#?} instead of {:?} when nested fields are hard to read on one line. The alternate Debug flag commonly adds indentation and line breaks.

Pretty Debug is still Debug output. It is intended for inspection and diagnostics, not as a stable serialization or public text format. See pretty Debug for that boundary.

Arrays whose elements implement Debug can use the same {:?} syntax directly:

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/print_values_pages.rs#debug-print-array
let numbers = [10, 20, 30];
println!("{numbers:?}");

You do not need to iterate over the array just to inspect it while debugging.

Use Display for deliberate user-facing text

Section titled “Use Display for deliberate user-facing text”

If the struct needs a stable, intentional human-readable representation, implement Display and print it with {} instead of exposing the derived Debug structure.

See implement Display for a Rust struct for a checked implementation and Debug vs Display for choosing between the two traits.