Sub topic 2
Debug: output meant for programmers
Prerequisites: basic Rust syntax, structs, enums, cargo run, and a basic understanding of traits.
Debug is a Rust trait for programmer-facing output. Its format placeholder is {:?}. Debug output may include type-like structure, field names, quotes, and escape characters. It is useful for logs and troubleshooting, but it is not usually a stable format for users or data files.
Display ({}) and Debug ({:?}) are separate because they serve different purposes. A user-facing value might need a short label, while a programmer needs to inspect its internal fields.
Deriving `Debug` for your types
The compiler can generate a Debug implementation for many structs and enums:
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 1, y: 2 };
println!("{:?}", point);
println!("{:>20?}", point);
}The first line prints something like Point { x: 1, y: 2 }. The second applies right alignment to the complete Debug representation.
Every field must also implement Debug. Standard types such as integers, strings, vectors, and options already do.
Readable nested output with `{:#?}`
Add # before ? to use alternate, pretty-printed Debug output:
#[derive(Debug)]
struct User {
name: String,
tags: Vec<String>,
}
fn main() {
let user = User {
name: "Ada".into(),
tags: vec!["rust".into(), "debug".into()],
};
println!("{:#?}", user);
}Rust places fields and nested values on separate, indented lines. This is easier to scan for large structs, vectors, and enums.
Width, fill, and alignment
A format width sets a minimum number of characters. Alignment can be left (<), centered (^), or right (>). A fill character goes before the alignment marker:
fn main() {
println!("[{:<8}]", "rust");
println!("[{:^8}]", "rust");
println!("[{:*>8}]", 42);
}Precision, sign, and zero padding
Precision controls digits after the decimal point for floating-point output. + always shows a sign, and 0 pads numeric output with zeroes:
fn main() {
println!("[{:06.2}]", 3.14159); // [003.14]
println!("{:+}", 5); // +5
}These options describe numeric formatting. They do not generally change the structure produced by Debug.
Exercise
Which placeholder should you use to inspect a derived struct, and which form makes nested output easier to read?
Show answer
Use {:?} for compact Debug output and {:#?} for pretty-printed, indented output.