Rust pretty print a struct with {:#?}
To pretty print a Rust struct for debugging, derive or implement Debug and format the value with {:#?}. The alternate Debug form commonly adds line breaks and indentation, making nested values easier to inspect.
#[derive(Debug)]
struct Request {
method: &'static str,
retries: u8,
}
let request = Request {
method: "GET",
retries: 2,
};
let pretty = format!("{request:#?}");
assert!(pretty.contains('\n'));
assert!(pretty.contains("method"));
assert!(pretty.contains("retries"));Pretty print a Rust struct
Section titled “Pretty print a Rust struct”{:?} requests compact Debug output. {:#?} adds the alternate flag and asks the Debug implementation for its pretty representation.
For ordinary structs and enums, #[derive(Debug)] is usually enough. Pretty Debug then works automatically when every field also implements Debug.
When pretty Debug helps
Section titled “When pretty Debug helps”Compact Debug is convenient for a small value on one line. Nested structs, enums, maps, and collections quickly become hard to scan.
Pretty Debug trades vertical space for structure. It is useful while reading local diagnostics, test failures, and temporary inspection output.
Pretty does not mean stable
Section titled “Pretty does not mean stable”The standard library does not promise a stable textual format for derived Debug. Rust may change the representation between versions, and a custom type can change its implementation at any time.
Do not use {:#?} as a serialization format, cache key, protocol, persistent file format, or parser input you control. If exact machine-readable output matters, use an explicit serialization format.
Derived and manual Debug
Section titled “Derived and manual Debug”A manual implementation can use the Formatter debug builders such as debug_struct, debug_tuple, or related helpers, which also support the alternate pretty form.
A completely custom Debug implementation controls its own representation. Pretty output is therefore a request to the implementation, not a guarantee that every type will have the same layout.
The # flag is trait-dependent
Section titled “The # flag is trait-dependent”The same # flag means something different with hexadecimal, octal, or binary formatters - there it requests a prefix such as 0x or 0b.
See alternate formatting for the broader rule: # asks the active formatting trait for its alternate representation.