capypad
0 Tage Serie
rust / intermediate
Snippet

Benutzerdefinierte Debug- und Display-Formatierung

Rusts Formatierungstraits ermöglichen benutzerdefinierte Ausgabe für Ihre Typen. Das Debug-Trait ist auto-ableitbar und ermöglicht den {:?} Formatierungsbezeichner. Display erfordert manuelle Implementierung und unterstützt {} für benutzerfreundliche Ausgabe. Beide Traits erfordern die Rückgabe von std::fmt::Result und verwenden das write!-Makro des Formatter-Structs. Die Implementierung von Display ermöglicht auch andere Traits wie Octal, Binary und LowerHex durch 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);
}
Erklärung
1
impl fmt::Debug for Point
Debug-Trait ermöglicht {:?}-Formatierung mit benutzerdefinierter Darstellung
2
write!(f, "Point {{ x: {:.2}, y: {:.2} }}", self.x, self.y)
Formatierung mit 2 Dezimalstellen unter Verwendung des write!-Makros des Formatters
3
impl fmt::Display for Point
Display ermöglicht {}-Formatierung für println!-Makros
4
write!(f, "({}, {})", self.x, self.y)
Einfaches Koordinatenformat für menschenlesbare Ausgabe