How to Use the dbg! Macro for Quick Debugging

The `dbg!` macro is a built-in Rust tool that evaluates an expression, prints its value along with the source file and line number to stderr, and then returns the original value so execution continues uninterrupted.

The dbg! macro is a built-in Rust tool that evaluates an expression, prints its value along with the source file and line number to stderr, and then returns the original value so execution continues uninterrupted. It is the fastest way to inspect variables or intermediate results without setting up a full debugger or adding verbose println! statements.

Use dbg! directly around any expression you want to inspect. It works seamlessly in both debug and release builds, though the output is suppressed in release mode by default unless you explicitly enable it.

Here is a simple example showing how it evaluates and returns a value:

fn main() {
    let x = 10;
    let y = dbg!(x + 5); // Prints: [src/main.rs:3] x + 5 = 15, then returns 15
    
    println!("y is {}", y); // Output: y is 15
}

You can also nest dbg! calls or use them in complex expressions to trace logic flow. Note that it prints to stderr, so it won't interfere with standard output logs.

fn calculate_total(price: f64, tax_rate: f64) -> f64 {
    let subtotal = price * 1.0;
    let tax = dbg!(subtotal * tax_rate); // Inspect tax calculation
    let total = subtotal + tax;
    
    dbg!(total) // Inspect final result before returning
}

fn main() {
    let result = calculate_total(100.0, 0.08);
    println!("Final: {}", result);
}

When running this, you will see output like [src/main.rs:5] subtotal * tax_rate = 8.0 followed by the final result. This is particularly useful in loops or conditionals where you need to see state changes without breaking execution.

If you need to suppress the output in release builds but keep it in debug builds, you can wrap it with #[cfg(debug_assertions)], though dbg! is already optimized to be a no-op in release builds by default in many toolchains. For more complex debugging scenarios involving multiple variables or conditional breakpoints, consider using the std::panic hook or an external debugger like lldb or gdb, but for quick ad-hoc checks, dbg! is the standard choice.