Sub topic 17
Quick inspection with dbg!
This chapter assumes you know println!, the Debug trait, and #[derive(Debug)] from earlier chapters. It also assumes you know basic ownership and moves.
What dbg! does
dbg! is a macro for looking at a value while you debug. It prints the source file, line, and column. It then prints the expression as written and its value formatted with {:#?}. After that it returns the value, so you can wrap it around part of an expression without changing what the program computes.
fn main() {
let a = 3;
let b = dbg!(a * 2) + 1;
dbg!(b);
}The program prints this to standard error:
[src/main.rs:3:13] a * 2 = 6
[src/main.rs:4:5] b = 7The first call prints 6 and hands it back, so b becomes 7. You don't need a temporary variable or a separate println!.
Differences from println!
| Feature | `println!` | `dbg!` |
|---|---|---|
| Output stream | Standard output | Standard error |
| Format used | Whatever you write | Always `{:#?}` |
| Shows expression text | No | Yes |
| Shows file, line, column | No | Yes |
| Returns the value | No (returns `()`) | Yes |
| Requires | `Display` or `Debug` as chosen | `Debug` |
Because dbg! writes to standard error, its output stays out of the way when you redirect or pipe standard output.
Ownership
dbg! takes its argument by value. For a type that is not Copy, the call moves it. Because dbg! returns the value, you can use the result. If you discard it, the value is dropped.
fn main() {
let names = vec![String::from("Ada"), String::from("Grace")];
dbg!(&names);
println!("{} names", names.len());
}Passing &names moves only a reference, so names is still usable afterward. Without the &, the second line would fail to compile with a "borrow of moved value" error.
Other forms
dbg!()with no arguments prints only the file and line. Use it to check that a branch runs.dbg!(a, b)with several arguments prints each one on its own and returns a tuple of the values.
Gotchas
- The type must implement
Debug. Add#[derive(Debug)]to your own types. dbg!is not removed in release builds. It prints whenever it runs, so delete the calls before you ship.- The output always uses the multi-line
{:#?}layout, which can be long for large collections. Useprintln!("{:?}", x)when you want one line.
Exercise
This code fails to compile. Why, and what is the smallest change that fixes it? fn main() { let text = String::from("hello"); dbg!(text); println!("{}", text); }
Show answer
dbg!(text) takes text by value and moves it, and the returned value is discarded. The later println! then uses a moved value. Change the call to dbg!(&text); so only a reference is moved and text stays usable.