Sub topic 6
Debug: output meant for programmers
This chapter assumes you can run programs with cargo run, that you know what a trait is, and that you have seen {} placeholders in println!. The previous chapter covered Display, which produces text for end users. This chapter covers Debug, its counterpart for the people who write and maintain the program.
What Debug is
Debug is a trait in std::fmt. A type that implements it can be formatted with the {:?} placeholder. Its one required method has the same signature as the one in Display:
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::ResultThe two traits differ in intent. Display output is for the person using your program, so it should be polished and should contain only what that person needs. Debug output is for the person writing the program, so it should show the structure and exact contents of a value, even if that looks noisy.
Almost every type in the standard library implements Debug. Many of them have no Display at all.
Using {:?}
Put ? after the colon in a placeholder. All the argument forms from earlier chapters still work: positional, named, and inline captured.
fn main() {
println!("{:?}", 42);
println!("{:?}", 2.0_f64);
println!("{:?}", "hi\n\"there\"");
println!("{:?}", 'x');
println!("{:?}", vec![1, 2, 3]);
println!("{:?}", (1, "a", 2.5));
println!("{:?}", Some("x"));
println!("{:?}", ());
}This prints:
42
2.0
"hi\n\"there\""
'x'
[1, 2, 3]
(1, "a", 2.5)
Some("x")
()Each value is printed the way you would write it as a Rust literal. Strings keep their quotes, and special characters are escaped. Characters use single quotes. Collections show their brackets and separators. The float 2.0 keeps its .0, while {} would print 2.
Why Debug output looks different from Display
Debug output shows details that Display hides.
| Value | `{}` | `{:?}` |
|---|---|---|
| `"abc "` | `abc ` | `"abc "` |
| `"a\tb"` | `a` and `b` separated by a tab | `"a\tb"` |
| `2.0_f64` | `2` | `2.0` |
| `'x'` | `x` | `'x'` |
| `Some(3)` | does not compile | `Some(3)` |
The quotes and escapes make invisible problems visible. A trailing space, a stray newline, or a tab shows up in the output, where plain {} would hide it. When a string comparison fails for no obvious reason, print both sides with {:?}.
Why there are two traits
Rust splits formatting into two traits because the two jobs conflict.
- Display needs a decision. A
Vec<i32>has no single correct user-facing form. It could be1, 2, 3, one item per line, or something else. The standard library does not guess, soVecdoes not implementDisplay. - Debug needs no decision. Any value can be shown as its structure. For that reason
Debugcan be generated automatically with#[derive(Debug)], which the next chapter covers.Displaycan never be derived.
If you try to print a Vec with {}, the compiler rejects it:
error[E0277]: `Vec<{integer}>` doesn't implement `std::fmt::Display`The fix is {:?}, or writing your own formatting if the output is meant for users.
Debug for standard collections and errors
Collections print their elements with Debug, recursively. Nesting works to any depth. Maps print as {key: value}:
use std::collections::BTreeMap;
fn main() {
let mut scores = BTreeMap::new();
scores.insert(1, "ann");
scores.insert(2, "bo");
println!("{:?}", scores);
let nested = vec![Some(vec![1, 2]), None];
println!("{:?}", nested);
println!("{:?}", "abc".parse::<i32>());
}The output is:
{1: "ann", 2: "bo"}
[Some([1, 2]), None]
Err(ParseIntError { kind: InvalidDigit })The example uses BTreeMap because it keeps keys sorted. A HashMap prints in an unspecified order that can change between runs.
The last line shows why Debug matters for errors. ParseIntError has a Display message, but Debug tells you the exact error variant.
Wrapper types forward to the value inside them. A &T, Box<T>, or Rc<T> prints the same as the T it points to, as long as T implements Debug.
Formatting flags with Debug
Most flags from the specifier chapters work with ?. You write them before the ?.
fn main() {
println!("[{:5?}]", 42);
println!("[{:5?}]", Some(1));
println!("{:.1?}", vec![1.26, 2.0]);
println!("{:x?}", vec![255, 16]);
println!("{:X?}", vec![255, 16]);
}This prints:
[ 42]
[Some( 1)]
[1.3, 2.0]
[ff, 10]
[FF, 10]Three points to notice:
- Flags are passed down to the inner values.
{:5?}onSome(1)pads the1, not the whole textSome(1). A precision such as.1is applied to every float in a collection. x?andX?print integers inside any Debug output in hex. This is useful for byte buffers.- Not every
Debugimplementation honours every flag. If you need the whole output padded as one unit, build aStringfirst and pad that.
Where Debug is required
You will meet Debug bounds outside of println!:
assert_eq!andassert_ne!print both sides when they fail, so both operand types must implementDebug.Result::unwrapandexpectrequire the error typeE: Debug, because they print it when they panic.Option::unwrapanddbg!have similar needs.dbg!, covered in a later chapter, requiresDebugon the value it prints.
You can also write your own generic code that prints values. Use a bound:
use std::fmt::Debug;
fn show_all<T: Debug>(items: &[T]) {
for (i, item) in items.iter().enumerate() {
println!("{i}: {item:?}");
}
}
fn main() {
show_all(&["a", "b"]);
show_all(&[Some(1), None]);
}The output is:
0: "a"
1: "b"
0: Some(1)
1: NoneWithout T: Debug, the call {item:?} would not compile. The compiler cannot know that an arbitrary T can be formatted.
Pitfalls
- Using
{:?}where{}is intended. Output such as"alice"with quotes in a user-facing message usually means the wrong trait was chosen. - Expecting a stable layout. Test code should compare values, not their Debug strings.
- Forgetting that Debug is not automatic. Your own structs and enums do not implement
Debuguntil you derive or write it. Printing them with{:?}before that gives a compile error.
Exercise
What does println!("{:?}", "a\tb") print, and how does it differ from println!("{}", "a\tb")?
Show answer
The first prints "a\tb": surrounding quotes, and a backslash followed by t instead of a real tab. The second prints a, a tab character, then b, with no quotes.
Exercise
println!("{}", Some(3)); does not compile. Why, and how do you fix it?
Show answer
Option<i32> implements Debug but not Display, because the standard library does not choose a user-facing form for it. Use println!("{:?}", Some(3));, which prints Some(3). If you need user-facing text, match on the option and print the inner value with {}.
Exercise
What does println!("{:.2?}", vec![1.0, 2.555]) print?
Show answer
[1.00, 2.56] or [1.00, 2.55], depending on how the float 2.555 is stored. The precision applies to every element, so each float shows exactly two decimals. The point of the question is that the flag reaches the inner values.