David's Blog

TIL: Print and return any expression with the Rust dbg macro

It's a fairly common workflow to add print statements when debugging why a small program or test doesn't work (and when I'm too lazy to drop into a debugger).

Today I learned about a builtin macro in Rust that does this without adding additional lines or requiring formatting a string with the contents of some variable(s): The dbg macro will accept any expression, print it, and also return the result:

  Prints and returns the value of a given expression for quick and dirty debugging.

  

It seems to have pretty nice default output too: the file and line number, the expression and the result of the expression. So you can just add the macro around any expression and get some nice debug output. One example from the docs:
let a = 2;
let b = dbg!(a * 2) + 1;
// ^-- prints: [src/main.rs:2] a * 2 = 4
assert_eq!(b, 5);