liveBook · Manning

Dbg! macro

As explained in Learn Rust in a Month of Lunches

The dbg! macro evaluates an expression, prints its source and value for debugging, and returns the value.

Use dbg! to inspect an expression while your program runs. It prints the source location, expression text, and value, then returns the value so you can wrap code without changing its result. section 9.2 section 22.3

fn main() {
    let mut my_number = dbg!(9);
    dbg!(my_number += 10);
    let new_vec = dbg!(vec![8, 9, 10]);
    let double_vec = dbg!(new_vec.iter().map(|x| x * 2).collect::<Vec<i32>>());
    dbg!(double_vec);
}

This example wraps a mutation, a vector, and an iterator pipeline to show how dbg! can reveal intermediate values. section 9.2

The output includes the expression being evaluated, which helps locate unexpected values. A mutation expression can return (), so dbg!(my_number += 10) prints () rather than the updated number. section 9.2 section 22.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Shows expression-level use and traces macro arms that print values and return expressions.
Examples
Uses a number, a mutation, a vector, and a mapped iterator to demonstrate printed values.
What you can do after
Diagnose/debug with dbg! by wrapping expressions to inspect values while retaining their results.
How it connects
Connects dbg! with iterators, closures, .inspect(), and macro_rules!.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.