Debugging with and without parameter in Rust

Reading Time: 1 minute

Rust 1.32.0 introduced a macro dbg! for quick and dirty debugging with which you can inspect the value of a given expression. In one of my previous blogs Are you still using println in Rust for debugging? I explained about this macro in detail.

Rust 1.35.0 announced an improvement in this macro to make it more usable for Rustaceans. Now you can trace any fine and line number using this macro without passing any parameter. If you go through above blog link, you will see, in the earlier version, you have to pass some value for inspection.
Let’s see an example of this macro without parameter:-

fn main() {
    dbg!();
    fibonacci(5);
}
fn fibonacci(n: u32) -> u32 {
    if n <= 2 {
        1
    } else {
        fibonacci(n - 1) + fibonacci(n - 2)
    }
}

Output is:-

[src/main.rs:2]

To effectively debug the code, this macro is very useful. You can trace the line number and file, wherever you want. You can see the state of code variables by passing value in this macro.

Since this macro is intended as a debugging tool, so it should not be mentioned in the final code. Cargo clippy has added a link to prevent this, which is dbg_macro. This lint is yet to be released. Once it gets released, you can use it.

I hope you get some idea of how to use this debugging macro. Thanks for reading this.


Knoldus-blog-footer-image

Written by 

Ayush is the Sr. Lead Consultant @ Knoldus Software LLP. In his 10 years of experience he has become a developer with proven experience in architecting and developing web applications. Ayush has a Masters in Computer Application from U.P. Technical University, Ayush is a strong-willed and self-motivated professional who takes deep care in adhering to quality norms within projects. He is capable of managing challenging projects with remarkable deadline sensitivity without compromising code quality.

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!