Trait Display e Debug in Rust
Livello 5402 battiture
Display definisce il formato per l'utente usato da {}, e Debug quello per lo sviluppatore usato da {:?}. Qui entrambi sono scritti a mano con write!.
Codice Rust
// fmt fornisce i trait Display/Debug e Formatter1use std::fmt;2 3struct Point {4 x: i32,5 y: i32,6}7 // Display viene usato dal segnaposto {}8impl fmt::Display for Point {9 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Scrive la forma breve (3, 4) nel formatter10 write!(f, "({}, {})", self.x, self.y)11 }12}13 // Debug viene usato da {:?}; scritto a mano invece di #[derive(Debug)]14impl fmt::Debug for Point {15 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // {{ e }} sono graffe di escape che stampano { e }16 write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)17 }18}19 20fn main() {21 let p = Point { x: 3, y: 4 }; // Usa Display: stampa (3, 4)22 println!("{}", p); // Usa Debug: stampa Point { x: 3, y: 4 }23 println!("{:?}", p);24}Output
(3, 4)
Point { x: 3, y: 4 }
Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.
Simboli in questo codice
I simboli che digiti in questo codice Rust e quante volte compaiono.
:× 23,× 15{× 15}× 15"× 8(× 8)× 8;× 4!× 4.× 4