Skip to content

Inspect values with Debug and dbg!

Debug is the formatting trait for programmer-facing output. Use {:?} for compact output and {:#?} for the alternate, pretty representation.

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/reference_examples.rs#debug-formats
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

let point = Point { x: 3, y: 4 };
let compact = format!("{point:?}");
let pretty = format!("{point:#?}");

dbg!(expression) prints the source location, expression text, and its Debug value to stderr. It then returns the evaluated value unchanged.

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/reference_examples.rs#debug-expression
let width = 6;
let area = dbg!(width * 4);
assert_eq!(area, 24);

dbg! is active in release builds too. Its exact text format is not a stable interface, so do not parse it or use it as application output.

dbg! takes and returns its input. For non-Copy values, calling dbg!(value) moves the value into the macro and back out. Borrow when the result is not being rebound:

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/reference_examples.rs#debug-borrow
let label = String::from("ready");
dbg!(&label);
assert_eq!(label, "ready");

For durable application diagnostics, use a logging or tracing facility. This page covers inspection output only; it does not claim to diagnose compiler errors.