capypad
0 day streak
rust / intermediate
Snippet

Custom Debug and Display Formatting

Rust's formatting traits enable custom output for your types. The Debug trait is auto-derivable and allows {:?} format specifier. Display requires manual implementation and supports {} for user-friendly output. Both traits require returning std::fmt::Result and use the Formatter struct's write! macro. Implementing Display also enables other traits like Octal, Binary, and LowerHex through delegation.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use std::fmt;
 
struct Point {
x: f64,
y: f64,
}
 
impl fmt::Debug for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Point {{ x: {:.2}, y: {:.2} }}", self.x, self.y)
}
}
 
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
 
fn main() {
let p = Point { x: 3.14159, y: 2.71828 };
println!("Display: {}", p);
println!("Debug: {:?}", p);
}
Breakdown
1
impl fmt::Debug for Point
Debug trait enables {:?} formatting with custom representation
2
write!(f, "Point {{ x: {:.2}, y: {:.2} }}", self.x, self.y)
Format with 2 decimal places using Formatter's write! macro
3
impl fmt::Display for Point
Display enables {} formatting for println! macros
4
write!(f, "({}, {})", self.x, self.y)
Simple coordinate format for human-readable output