Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Rust dbg! macro

Reference for the Rust dbg! macro: printing an expression and its value to stderr with file and line, returning the value, ownership and removal.

dbg!(expr) prints the source text of an expression, its value in {:#?} pretty-debug form, and the file and line, all to standard error. Then it returns the value, so you can wrap it around part of an expression without changing what the program computes.

It is a debugging tool, not a logging system: the output is for you, and you should remove the calls before committing. The value must implement Debug.

Rust
let total = dbg!(a * b) + 1;

Try it

Rust Wrapping part of an expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Several values and ownership

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
dbg!(expr)
dbg!(expr1, expr2, ...)   // returns a tuple
dbg!()                    // prints only the file and line
Name Description
expr Any expression whose type implements Debug.

Returns: the value of expr (moved, not copied), or a tuple of all values when several are given, or () with no arguments. Panics: only if writing to stderr fails in a way eprintln! would also panic on.

Usage notes

  • Output goes to stderr, so it does not mix with normal program output on stdout. In our runner the tool shows stderr along with stdout.
  • It moves its argument. dbg!(s) with a String gives s back, but if you do not use the result, s is gone. Use dbg!(&s) to just look.
  • Not stripped in release. Unlike debug_assert!, dbg! stays in release builds, so delete it when you are done. Clippy has a dbg_macro lint.
  • Evaluation order follows normal expression rules; each argument is evaluated once.
  • Format is pretty-printed {:#?}, which can be long for large structures.
  • Output includes the path as the compiler saw it, so it varies with where you build.