Sub topic 4
Compact and pretty Debug output
This chapter assumes you know how #[derive(Debug)] works and can read a println! format string. It covers the two output shapes that Debug produces and when to use each.
Two shapes, one trait
A type that implements Debug can be printed in two ways. The format specifier picks the shape. The trait has only one fmt method, and the formatter carries a flag that says whether the "alternate" form was requested.
{:?}prints the value compactly on one line.{:#?}prints the value "pretty", with one field or element per line and four-space indentation.
Seeing the difference on nested data
The difference matters most when values are nested. This program prints the same vector both ways.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug)]
enum Shape {
Dot(Point),
Line { from: Point, to: Point },
}
fn main() {
let shapes = vec![
Shape::Dot(Point { x: 1, y: 2 }),
Shape::Line {
from: Point { x: 0, y: 0 },
to: Point { x: 3, y: 4 },
},
];
println!("{:?}", shapes);
println!("{:#?}", shapes);
}The compact line is:
[Dot(Point { x: 1, y: 2 }), Line { from: Point { x: 0, y: 0 }, to: Point { x: 3, y: 4 } }]The pretty form is:
[
Dot(
Point {
x: 1,
y: 2,
},
),
Line {
from: Point {
x: 0,
y: 0,
},
to: Point {
x: 3,
y: 4,
},
},
]Pretty output adds a trailing comma after every item. This is why it can be pasted into a diff and compared line by line.
Choosing a shape
| Situation | Use |
|---|---|
| Log lines, one record per line | `{:?}` |
| Inspecting a large nested value | `{:#?}` |
| Assertion failure messages | Either; `assert_eq!` already prints with `{:?}` |
| Quick look at an expression | `dbg!` |
The dbg! macro prints to standard error, not standard output. It uses the pretty form, and it adds the file, line, and source text of the expression. It also returns its argument, so you can wrap an expression without changing the program's behavior.
fn main() {
let total = dbg!(2 + 3) * 4;
println!("{}", total);
}Common surprises
- Debug output is not a stable format. Don't parse it or compare it in tests that must survive compiler upgrades. Use
serdeor a hand-written format for data that other code reads. - Strings in Debug output are quoted and escaped.
println!("{:?}", "a\nb")prints"a\nb"with the backslash visible, which makes hidden characters easy to spot. - A
HashMapprints its entries in an unspecified order that can change between runs. Don't compare its Debug output in tests. - Both specifiers need
Debugon every field. If one field's type lacks it, the derive fails to compile. The error points at that field.
Exercise
A struct Config derives Debug and has the fields name: String and retries: u32. For Config { name: "db".to_string(), retries: 3 }, what does {:?} print, and how many lines does {:#?} print?
Show answer
{:?} prints Config { name: "db", retries: 3 }. {:#?} prints four lines: Config {, name: "db",, retries: 3,, and }.