Sub topic 8
Readable nested output with {:#?}
This chapter assumes you can derive Debug on structs and enums and print with {:?}. It covers the alternate flag # applied to Debug, which gives indented multi-line output. You will see what the layout looks like, how other format options interact with it, and what a manual Debug implementation must do to support it.
Why one-line Debug stops being useful
{:?} writes everything on one line. That is fine for a small value. For a struct holding a Vec of structs, the line grows past the terminal width and you have to count brackets to find a field.
{:#?} is the same Debug trait with the alternate flag # turned on. The derived implementation responds by putting each field, element, and variant payload on its own line. It indents nested levels by four spaces and adds a trailing comma after every item.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug)]
struct Shape {
name: String,
corners: Vec<Point>,
label: Option<&'static str>,
}
fn main() {
let s = Shape {
name: "tri".to_string(),
corners: vec![Point { x: 0, y: 0 }, Point { x: 4, y: 0 }],
label: None,
};
println!("{:?}", s);
println!("{:#?}", s);
}The first call prints one line:
Shape { name: "tri", corners: [Point { x: 0, y: 0 }, Point { x: 4, y: 0 }], label: None }The second prints:
Shape {
name: "tri",
corners: [
Point {
x: 0,
y: 0,
},
Point {
x: 4,
y: 0,
},
],
label: None,
}Each nesting level adds one indent step, so the layout follows the shape of the data.
How the layout is decided
The derived Debug code does not measure line length. It never decides that a short value "fits" and keeps it compact. With #, every struct, tuple, list, set, and map is expanded, even a struct with a single field.
The rules are small:
- Named-field structs and struct-like enum variants print
Name {and onefield: value,per line. - Tuple structs, tuple variants, and tuples print
Name(or(with one value per line. - Sequences (
Vec, arrays, slices,VecDeque) and sets print[or{with one element per line. - Maps print
key: value,per line. - Unit values such as
Noneor a unit enum variant stay as a single word. - Empty collections stay compact:
[]and{}.
The next program shows enums, a map, and a tuple. It uses BTreeMap because its keys come out in sorted order, so the output is the same on every run.
use std::collections::BTreeMap;
#[derive(Debug)]
enum Status {
Active,
Suspended { days: u32 },
Pending(String),
}
#[derive(Debug)]
struct Account {
id: u32,
status: Status,
tags: BTreeMap<String, i32>,
pair: (i32, f64),
}
fn main() {
let mut tags = BTreeMap::new();
tags.insert("a".to_string(), 1);
let acct = Account {
id: 7,
status: Status::Suspended { days: 3 },
tags,
pair: (1, 2.5),
};
println!("{:#?}", acct);
println!("{:#?}", vec![Status::Active, Status::Pending("x".to_string())]);
}Output:
Account {
id: 7,
status: Suspended {
days: 3,
},
tags: {
"a": 1,
},
pair: (
1,
2.5,
),
}
[
Active,
Pending(
"x",
),
]Notice that Some(1) with {:#?} becomes three lines (Some(, 1,, )). That surprises people the first time, because Option is a tuple-like enum and follows the same rule.
Choosing between the two forms
The single-line form works better with tools such as grep, because one record is one line. The pretty form works better when a person is reading a deep value and wants to find one field.
Other format options still apply
Width, precision, and sign options are passed down to the leaf values inside a Debug print. Combined with #, they apply to every number inside the structure.
fn main() {
let data = vec![1.0_f64, 2.34];
println!("{:.1?}", data);
println!("{:#.1?}", data);
println!("{:03?}", vec![1, 22]);
}Output:
[1.0, 2.3]
[
1.0,
2.3,
]
[001, 022]Here .1 limits every float to one decimal place, and 03 zero-pads every integer to three digits. The options apply to each element, not to the whole printed text. A width such as {:10?} on a Vec<i32> pads each number, not the list as a whole.
Pretty output in a manual Debug implementation
If you derive Debug, # support comes free. If you write Debug by hand with write!, you get only the layout you wrote, and {:#?} prints the same as {:?}.
The helpers debug_struct, debug_tuple, debug_list, and debug_map on Formatter check the alternate flag for you. Prefer them over write! in a Debug implementation.
use std::fmt;
struct Config {
name: String,
retries: u32,
}
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Config")
.field("name", &self.name)
.field("retries", &self.retries)
.finish()
}
}
fn main() {
let c = Config { name: "main".to_string(), retries: 3 };
println!("{:?}", c);
println!("{:#?}", c);
}Output:
Config { name: "main", retries: 3 }
Config {
name: "main",
retries: 3,
}If you must check the flag yourself, f.alternate() returns true when # was given. Most code never needs it.
Common mistakes
- Using
{:#}on a type that has only Debug.{:#}is the alternate flag onDisplay, notDebug. It does not compile unless the type implementsDisplay. Write{:#?}, with the?. - Expecting compact output for small values. A struct with one field still takes three lines. If you want compact output for some values, use
{:?}. - Parsing pretty output. The layout is meant for people. The standard library does not promise it will stay the same between Rust versions, so do not write a program that parses it. Use a serialization format such as JSON for that.
- Forgetting that strings keep their quotes. Debug prints
"tri", nottri, in both forms.
Summary
{:#?} is {:?} plus the alternate flag. Derived Debug implementations respond by expanding every struct, tuple, list, set, and map onto indented lines with trailing commas. Other format options still apply to the leaf values. A hand-written Debug gets the same behavior if it uses the debug_* helpers on Formatter.
Exercise
A type has #[derive(Debug)] and holds Some(5) in a field called limit. How many lines does that field take with {:#?}, and what are they? What does the field print as with {:?}?
Show answer
With {:#?} it takes four lines: limit: Some(, then 5, indented one level further, then ),. Counting the field name and its opening on one line, that is three lines for the value plus the surrounding trailing comma on the closing parenthesis. With {:?} it prints on one line as limit: Some(5).
Exercise
You write impl fmt::Debug for Id using write!(f, "Id({})", self.0). Does {:#?} print Id differently from {:?}? What change would make it do so?
Show answer
No. write! produces the same text regardless of the alternate flag. Replace it with f.debug_tuple("Id").field(&self.0).finish(), which checks the flag and prints Id( then 5, then ) on separate lines under {:#?}.