Debug Alternate Flag Pretty Prints
Custom Debug impls branch on f.alternate, so {:?} renders one compact line while {:#?} gets the pretty multi-line shape.
Code
use std::fmt;
struct Config {
name: String,
retries: u32,
}
// hand-written Debug: the alternate flag is true for {:#?}, which prints the pretty multi-line shape
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write!(
f,
"Config {{\n name: {:?},\n retries: {},\n}}",
self.name, self.retries
)
} else {
write!(f, "Config {{ name: {:?}, retries: {} }}", self.name, self.retries)
}
}
}
fn main() {
let config = Config { name: String::from("api"), retries: 5 };
println!("{config:?}");
println!("{config:#?}");
}What the demo prints
One Debug impl serves both forms by branching on f.alternate(). The compact {:?} prints Config { name: “api”, retries: 5 } on a single line, exactly the shape logs and one-line errors want.
The alternate {:#?} takes the other branch and prints the pretty multi-line shape, with name and retries each on their own indented line inside the braces. Both calls go through the same impl; the flag is the only difference.
Practical notes
- alternate() is true only for the {:#?} form.
- Pretty output embeds its own newlines and indentation.
Interactive Tools for This Topic
FAQ
- How do the two Debug forms differ?
- {:?} renders the compact single line and {:#?} sets the alternate flag, which the impl branches on to produce the indented multi-line output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.