Today I learned why I should use the dbg! macro instead of the println! macro for debugging in Rust.

What is the dbg! macro in Rust?

The dgb! macro is a macro that is similar to println! but that is designed specifically for debugging. Not only does it print the values you pass it, but it also adds a tag with the name of the file and the line from where the macro was called.

Here is an example of using the dbg! macro:

fn main() {
    dbg!("hello, world!");

If you run your program with cargo run now, this is what you get:

❯ cargo run
   Compiling borrowing v0.1.0 (/Users/rodrigogs/Documents/rust/borrowing)
    Finished dev [unoptimized + debuginfo] target(s) in 0.10s
     Running `target/debug/borrowing`
[src/] "hello, world" = "hello, world"

Notice the last line of the output, that shows the argument to the macro, along with the line of code from where the macro was called. It may look redundant to have "hello, world" = "hello, world" displayed there, but that is because the macro will show the expression that was used as its argument and it will show the value of that expression.

Here is another example program:

fn main() {
    dbg!(3 + 3);

This shows:

❯ cargo run
# ...
[src/] 3 + 3 = 6

Or this program:

fn main() {
    let x = 3;


❯ cargo run
# ...
[src/] x = 3

So, this is how you use the dbg! macro in Rust!

That's it for now! Stay tuned and I'll see you around!

Become a better Python 🐍 developer πŸš€

+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!

My book β€œPydon'ts” teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here πŸπŸš€.

Previous Post Next Post

Blog Comments powered by Disqus.