dbg! Macro Inspects Expression Values

Print expressions with dbg! to stderr along with file, line and the evaluated value, keeping the value usable inline so debugging never breaks the data flow.

RustData Integrity

Code

rustsnippet
24 lines
#[derive(Debug)]
enum Step {
    Working { items: usize },
}

fn normalize(input: &str) -> String {
    // dbg! 返回表达式求值结果本身,可以嵌在赋值链中间
    let trimmed = dbg!(input.trim());
    let lowered = dbg!(trimmed.to_lowercase());
    lowered
}

fn main() {
    // dbg! 输出到 stderr(file:line: 表达式 = 值),stdout 只留正式输出
    let step = Step::Working { items: dbg!(3 + 4) };
    println!("step: {step:?}");

    let value = dbg!(normalize("  MiXeD Case  "));
    println!("kept value: {value}");

    // 调试完删除 dbg! 即可;println! 需要额外占位符,dbg! 不用
    let sum = dbg!(1 + 2) * 10;
    println!("sum*10: {sum}");
}

What the code does

Count the functions normalize and main as the entire surface area of dbg! Macro Inspects Expression Values.

Using it

The primary signature is fn normalize(input: &str) -> String

Look for the step:, kept value:, sum*10: prefixes when the file runs; they tie each line to its step.

Start the program and main runs normalize one after another.

Key statements

fn normalize(input: &str) -> String {
// dbg! 返回表达式求值结果本身,可以嵌在赋值链中间
let trimmed = dbg!(input.trim());
let lowered = dbg!(trimmed.to_lowercase());
lowered
}

Interactive Tools for This Topic

FAQ

What does dbg! Macro Inspects Expression Values print when run?
Run it as a complete program — the output lines carry labels such as `step:`, `kept value:`, `sum*10:`.