Are you still using `println` in Rust for debugging?

Printing to standard output is a good way to trace through your code and troubleshoot potential problems. While coding, many programmers use a lot of println statements to see what is going on at different levels in their code. If you are from Java background, you would have used System.out.println() and System.err.println() methods. If you are from Scala background, you would have used println.

As a Rustacean, you are probably all too familiar with the macros like println and eprintln. Both do the same thing except that output of eprintln goes to io::stderr instead of io::stdout.

In this blog, I will explain about new debugging macro dbg, added in Rust 1.32.0
This is a macro for quick and dirty debugging with which you can inspect the value of a given expression.

Lets go through below examples and see the difference between println and dbg.

fn fibonacci(n: u32) -> u32 {

    if n <= 2 {
        println!("n <= 2");
        1
    } else {
        let n = fibonacci(n - 1) + fibonacci(n - 2);
        println!("n: {}", n);
        n
    }
}

Now the out of fibonacci(5)

n: 5
n: 4
n: 3
n: 2
n <= 2
n: 1
n <= 2
n: 2
n: 2
n <= 2
n: 3
n: 3
n: 2
n <= 2
n: 1
n <= 2
n: 2
n: 5

In the above output, it is hard to find information like which line, which step etc .We have to add some details in println to make it more clear. Now let’s see an example of dbg.

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

Now the output is

[main.rs:6] n <= 2 = false
[main.rs:6] n <= 2 = false
[main.rs:6] n <= 2 = false
[main.rs:6] n <= 2 = true
[main.rs:7] 1 = 1
[main.rs:6] n <= 2 = true
[main.rs:7] 1 = 1
[main.rs:9] fibonacci(n - 1) + fibonacci(n - 2) = 2
[main.rs:6] n <= 2 = true
[main.rs:7] 1 = 1
[main.rs:9] fibonacci(n - 1) + fibonacci(n - 2) = 3
[main.rs:6] n <= 2 = false
[main.rs:6] n <= 2 = true
[main.rs:7] 1 = 1
[main.rs:6] n <= 2 = true
[main.rs:7] 1 = 1
[main.rs:9] fibonacci(n - 1) + fibonacci(n - 2) = 2
[main.rs:9] fibonacci(n - 1) + fibonacci(n - 2) = 5

As you can see, we got more useful output without making any addition changes in the code.
If you are a println debugger, start using this powerful macro. Thanks for reading. This article was first published on the Knoldus blog.

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.

Leave a Reply

Knoldus Pune Careers - Hiring Freshers

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