Sub topic 4
Compact and pretty Debug output
This chapter assumes you know how #[derive(Debug)] works and can read format strings like {} and {:?}. Here you will learn what the two Debug layouts look like, how the formatter flags change them, and where they can surprise you.
Two layouts from one implementation
A type that implements Debug has one fmt method. The format string decides how that method behaves:
{:?}asks for the compact layout, which fits on one line.{:#?}asks for the pretty layout, which spreads the value over many indented lines.
The # sets the formatter's alternate flag. Derived implementations read that flag and change their layout. You write no extra code.
What derive produces
Derived output follows the shape of the type. Consider this program.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug)]
enum Shape {
Dot,
Circle { center: Point, radius: f64 },
Line(Point, Point),
}
fn main() {
let shapes = vec![
Shape::Dot,
Shape::Circle {
center: Point { x: 1, y: 2 },
radius: 1.5,
},
Shape::Line(Point { x: 0, y: 0 }, Point { x: 3, y: 4 }),
];
println!("{:?}", shapes);
println!("{:#?}", shapes[1]);
}The compact line is:
[Dot, Circle { center: Point { x: 1, y: 2 }, radius: 1.5 }, Line(Point { x: 0, y: 0 }, Point { x: 3, y: 4 })]The pretty block for shapes[1] is:
Circle {
center: Point {
x: 1,
y: 2,
},
radius: 1.5,
}The rules are the same for every derived type:
| Kind of value | Compact `{:?}` | Pretty `{:#?}` |
|---|---|---|
| Named-field struct or variant | `Point { x: 1, y: 2 }` | One field per line, indented 4 spaces |
| Tuple struct or variant | `Line(a, b)` | One element per line inside parentheses |
| Unit struct or variant | `Dot` | `Dot` |
| `Vec`, slice, array | `[1, 2]` | One element per line inside brackets |
| `Option` | `Some(3)` or `None` | `Some(` then the value indented, then `)` |
Pretty output puts a trailing comma after every item, including the last. That makes it easy to paste into Rust source or compare with a diff tool. An empty collection stays [] in both layouts.
Strings and characters are escaped
Debug is written for programmers, so it shows what is really in the value. Strings get quotes, and characters such as newlines and quotes are escaped.
fn main() {
let name: Option<&str> = Some("Ada \"Lovelace\"\n");
println!("{:?}", name);
println!("{}", name.unwrap());
println!("{:?} {:?}", 'a', '\t');
}The first line prints Some("Ada \"Lovelace\"\n"). The second prints the raw text, with a real line break at the end. The third prints 'a' '\t'. This makes Debug good for finding stray whitespace, and a poor choice for text shown to users. That job belongs to Display, covered in the next chapters.
Flags are passed down to the leaves
Other format flags work with Debug, and they apply to each primitive value inside, not to the whole.
fn main() {
println!("{:.1?}", vec![1.26, 2.0]);
println!("{:x?}", vec![255, 16]);
println!("{:5?}", Some(1));
}This prints:
[1.3, 2.0]
[ff, 10]
Some( 1){:.1?}sets precision for every float, which is useful for a long list of measurements.{:x?}and{:X?}print integers in lowercase or uppercase hex. This is handy for byte buffers.{:5?}pads the inner1to width 5, not the wholeSome(1). Do not expect{:10?}to align a struct in a column.
If you need a fixed-width column, format the value to a String first, then pad that string with {:>20}.
fn main() {
let text = format!("{:?}", Some(1));
println!("[{:>12}]", text);
}Printing for quick debugging: `dbg!`
The dbg! macro prints in the pretty layout. It writes to standard error, not standard output, so it will not mix with your program's real output. It also adds the file name, line number, and source text of the expression.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = dbg!(Point { x: 1, y: 2 });
let total = dbg!(p.x + p.y) * 2;
println!("{}", total);
}dbg! takes ownership of its argument and returns it, so you can wrap an expression in the middle of a computation without changing the result. Passing a non-Copy variable by name moves it. Write dbg!(&value) when you still need the value afterward.
Pretty output from manual implementations
A hand-written Debug built with debug_struct, debug_tuple, or debug_list also honors {:#?}. The helper methods check the alternate flag for you. If you write the output yourself with write!, you get exactly one layout, whatever the user asks for. Prefer the helpers unless you have a reason not to. The previous chapter's Credentials example does this.
Edge cases to know
- Map and set order.
HashMapandHashSetprint in iteration order, which can differ between runs. Tests that compare their Debug strings will fail at random. UseBTreeMapor sort the entries first. - Large values.
{:#?}on a deep structure can produce thousands of lines. Print a smaller part, such as{:#?}on one field, or use the compact form for logs. - Every field needs Debug.
#[derive(Debug)]fails to compile if any field's type lacksDebug. Derive it on that type, or write a manual implementation for the outer type that skips the field. - Secrets. A derived Debug prints every field. If a struct holds a password or token, a stray
{:?}in a log line leaks it. Hand-write Debug for such types. - Generics. For
struct Wrapper<T>, derive adds the boundT: Debug.Wrapper<NoDebug>simply has no Debug output.
Do not use `{:?}` output as user-facing text, such as an error message in a command-line tool. It exposes internal names and escapes characters, and its layout may change. Implement `Display` for that purpose.When to use each layout
Use {:?} for single-line log entries and for assert_eq! failure messages in short tests. Use {:#?} when reading a nested structure on a terminal, or when you want a diff-friendly dump in a file. Use dbg! while exploring and remove it before committing.
Exercise
What does println!("{:x?}", vec![255, 16]) print, and why does the width flag in {:5?} apply differently from what you might expect on Some(1)?
Show answer
The first prints [ff, 10], because x? asks Debug to show integers in lowercase hex. A width flag is passed down to each primitive value, so {:5?} on Some(1) prints Some( 1), padding only the inner number rather than the whole string.
Exercise
You want to inspect an intermediate value in the middle of an expression, in pretty layout, without disturbing the program's normal output or its result. Which tool do you use, and what must you watch for with non-Copy values?
Show answer
Use dbg!. It prints the pretty layout with the file and line to standard error and returns its argument. It moves the value it receives, so pass a reference, as in dbg!(&value), if you need the value afterward.