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
In this blog, I will explain about new debugging macro
This is a macro for quick and dirty debugging with which you can inspect the value of a given expression.
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
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
If you are a
