Sub topic 17
Quick inspection with dbg!
This chapter assumes you can derive Debug for a struct (covered earlier in this tutorial) and that you know the basics of ownership: a value is moved when you pass it by value. You should also know that println! writes to standard output and eprintln! writes to standard error.
What dbg! does
dbg! is a macro for temporary inspection while you develop. You wrap an expression in it. The macro does four things:
- It evaluates the expression once.
- It prints the source file, line, column, the expression text, and the value to standard error.
- It formats the value with pretty Debug, the same output as
{:#?}. - It returns the value, so the surrounding code behaves as if
dbg!were not there.
Because it returns the value, you can insert it into the middle of an existing expression without restructuring anything.
fn main() {
let a = 2;
let b = dbg!(a * 2) + 1;
dbg!(b);
}Running this prints the following to standard error:
[src/main.rs:3:13] a * 2 = 4
[src/main.rs:4:5] b = 5The 3:13 means line 3, column 13. The text a * 2 is the expression exactly as you wrote it. The value 4 was passed on, so b ends up as 5.
How it differs from println!
You could write println!("{:?}", a * 2) instead. The two differ in several ways.
| Feature | `println!("{:?}", x)` | `dbg!(x)` |
|---|---|---|
| Output stream | Standard output | Standard error |
| Shows location | No | Yes (file, line, column) |
| Shows expression text | No | Yes |
| Debug style | Compact unless you write `{:#?}` | Always pretty |
| Returns the value | No (returns `()`) | Yes |
| Takes ownership | No (borrows) | Yes, of the argument |
The standard error stream is the right place for debug output. A program that prints its real results to standard output can still be piped or redirected, and your debug lines will not corrupt that data. You can also capture them separately:
cargo run > results.txt 2> debug.txtInspecting inside an expression
Since dbg! passes its value through, you can place it anywhere an expression is allowed. This is useful for finding which step of a chain produces a surprising value.
fn main() {
let total: i32 = vec![1, 2, 3]
.into_iter()
.map(|n| dbg!(n * 10))
.filter(|n| *n > 10)
.sum();
println!("total = {total}");
}Each element prints a line such as [src/main.rs:4:18] n * 10 = 10. Then the program prints total = 50 to standard output. The filter still sees the same values, because dbg! returned them unchanged.
Recursive functions are another good fit. Wrapping both the condition and the result shows the call order:
fn factorial(n: u32) -> u32 {
if dbg!(n <= 1) {
dbg!(1)
} else {
dbg!(n * factorial(n - 1))
}
}
fn main() {
dbg!(factorial(4));
}Ownership: dbg! moves its argument
dbg! takes its argument by value. If the argument is a variable of a type that is not Copy, the variable is moved into the macro and moved out again as the return value. If you discard the return value, the original is gone.
fn main() {
let name = String::from("Ferris");
dbg!(name);
println!("{name}");
}This does not compile. The compiler reports that name was moved by the dbg! call and then borrowed afterwards. There are two fixes.
The first fix is to pass a reference. A reference is Copy, and it implements Debug whenever the thing it points to does. The printed expression text will include the &.
fn main() {
let name = String::from("Ferris");
dbg!(&name);
println!("{name}");
}The second fix is to use the return value, rebinding the variable: let name = dbg!(name);. Prefer the reference form for plain inspection, because it makes no change to ownership.
Types that are Copy, such as integers, are copied, so dbg!(b) in the first example left b usable.
Debug output of your own types
The value must implement Debug. For your own types, that means deriving it or writing it by hand, as covered in earlier chapters. Without it you get a compile error that says the trait bound Debug is not satisfied.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 1, y: 2 };
dbg!(&p);
}The output spreads over several lines, because dbg! always uses the {:#?} form:
[src/main.rs:9:5] &p = Point {
x: 1,
y: 2,
}If you wrote a manual Debug implementation, such as the one that hides a password, dbg! uses it too. The password stays hidden in debug output.
Several values and no values
With several comma-separated arguments, dbg! prints each one on its own line, in order, and returns them as a tuple:
fn main() {
let (n, s) = dbg!(1 + 1, "hi");
println!("{n} {s}");
}This prints two dbg! lines to standard error, 1 + 1 = 2 and "hi" = "hi", and then 2 hi to standard output.
With no arguments, dbg!() prints only the location, as [src/main.rs:LINE:COLUMN]. It is a quick way to check whether a branch of code runs at all:
fn main() {
let value = 7;
if value > 5 {
dbg!();
}
}Common errors and gotchas
- Use after move. Described above. Pass
&valueunless you intend to use the return value. - Missing Debug. Every value passed must implement
Debug. Add#[derive(Debug)]to your types. - Release builds.
dbg!is not removed in release mode. It prints incargo run --releasetoo. - Left-over calls in committed code. Nothing warns you if you forget a
dbg!. Search for it before committing, for example withgrep -rn "dbg!" src. - Cost. Pretty-printing a large collection on every loop iteration is slow and floods your terminal. Inspect one element or a summary instead.
- Tests. Under
cargo test, the test harness captures standard error output. You see thedbg!lines only for failing tests, or when you run with-- --nocapture.
Choosing between the tools
Use dbg! when you want to know what a value is at one point in the code and where that point is. Use println!("{:?}") when you want output on standard output, or a compact one-line form. Use eprintln! with your own message when you want a human-readable label that is not just the source text. Use a logging crate for anything permanent.
Exercise
The code let v = vec![1, 2, 3]; dbg!(v); println!("{}", v.len()); fails to compile. Why does it fail, and what is the smallest change that fixes it while still printing the vector with dbg!?
Show answer
dbg! takes its argument by value, so v is moved into the macro, and the returned vector is discarded. The later v.len() then uses a moved value. Changing the call to dbg!(&v); passes a reference instead, so v is still owned by main and v.len() compiles. Binding the result, let v = dbg!(v);, also works.
Exercise
A program prints its results with println! and also contains dbg! calls. You run cargo run > out.txt. Which output ends up in out.txt, and which appears on the terminal?
Show answer
out.txt receives only the println! output, because the redirect > captures standard output. The dbg! lines are written to standard error, so they still appear on the terminal.
Exercise
What do the values of x and y end up as in let (x, y) = dbg!(2 * 3, 4);, and how many lines does dbg! print?
Show answer
x is 6 and y is 4, because dbg! with several arguments returns them as a tuple. It prints two lines to standard error, one for 2 * 3 = 6 and one for 4 = 4, each with its own file, line, and column prefix.