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.
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
let point = Point { x: 3, y: 4 };
let compact = format!("{point:?}");
let pretty = format!("{point:#?}");What dbg! adds
Section titled “What dbg! adds”dbg!(expression) prints the source location, expression text, and its Debug value to stderr. It then returns the evaluated value unchanged.
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.
Borrow when you need the value afterward
Section titled “Borrow when you need the value afterward”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:
let label = String::from("ready");
dbg!(&label);
assert_eq!(label, "ready");Related references
Section titled “Related references”- Debug vs Display for choosing the representation by audience
- Pretty Debug with
{:#?}for multi-line inspection - Formatting traits for the trait behind each format suffix
For durable application diagnostics, use a logging or tracing facility. This page covers inspection output only; it does not claim to diagnose compiler errors.