Sub topic 8
Readable nested output with {:#?}
This chapter assumes you can derive Debug on a struct or enum and print it with {:?}. It builds on that.
The problem with one-line Debug
{:?} puts the whole value on one line. That works for small values. When structs hold other structs, vectors, and options, the line becomes hard to scan.
Adding the # flag gives {:#?}. The # is the alternate flag, and for Debug it selects pretty-printed output.
Comparing the two forms
#[derive(Debug)]
struct Address {
city: String,
zip: u32,
}
#[derive(Debug)]
enum Role {
Admin,
Member { team: String },
}
#[derive(Debug)]
struct User {
name: String,
address: Address,
roles: Vec<Role>,
nickname: Option<String>,
}
fn main() {
let user = User {
name: "Ada".to_string(),
address: Address { city: "London".to_string(), zip: 12345 },
roles: vec![Role::Admin, Role::Member { team: "core".to_string() }],
nickname: None,
};
println!("{:?}", user);
println!("{:#?}", user);
}The first call prints one long line:
User { name: "Ada", address: Address { city: "London", zip: 12345 }, roles: [Admin, Member { team: "core" }], nickname: None }The second call prints this:
User {
name: "Ada",
address: Address {
city: "London",
zip: 12345,
},
roles: [
Admin,
Member {
team: "core",
},
],
nickname: None,
}The layout rules
- Each field, element, or entry goes on its own line.
- Each nesting level adds four spaces of indentation.
- Every item ends with a comma, including the last one. This is why pretty output can be pasted into source code with few edits.
- Unit variants such as
AdminandNonestay on one line. - Tuple-like values expand too.
Some(5)prints asSome(, then5,on its own indented line, then).
Collections follow the same rules. A HashMap prints one key: value, pair per line inside braces.
Custom Debug and the pretty flag
You do not need to handle {:#?} yourself in a manual Debug implementation. The helpers debug_struct, debug_tuple, debug_list, and debug_map check the flag and switch layout on their own. If you build the output with plain write!, you get no pretty form.
When to use it
Use {:#?} when you inspect deeply nested data, such as parsed configuration or a syntax tree, or when you compare two values by eye. Use {:?} when you want one log line per event, because multi-line output breaks line-based log tools.
Exercise
Given let v = vec![Some(1), None];, what does println!("{:#?}", v); print?
Show answer
It prints the list with one element per line, and each element ends with a comma: [ Some( 1, ), None, ]
Exercise
You wrote impl fmt::Debug for Secret using write!(f, "Secret {{ user: {} }}", self.user). Why does {:#?} print the same single line as {:?}, and how do you fix it?
Show answer
write! only writes the exact text you give it, so it never looks at the alternate flag. Use f.debug_struct("Secret").field("user", &self.user).finish(), which switches to the multi-line layout when {:#?} is used.