Display and Debug in Rust
Debug is for programmers, Display is for people — derive one, write the other.
use std::fmt;
#[derive(Debug)]
struct Run {
lang: String,
tpm: u32,
accuracy: f64,
}
impl fmt::Display for Run {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} at {} tpm ({:.1}%)", self.lang, self.tpm,
self.accuracy)
}
}
fn main() {
let run = Run {
lang: "rust".to_string(),
tpm: 104,
accuracy: 97.5,
};
println!("{run}");
println!("{run:?}");
println!("{}", run.to_string().len());
}
How it works
#[derive(Debug)]gives you{:?}for free.Displayis hand-written and enables{}andto_string.{:#?}pretty-prints the derived Debug form.
Keywords and builtins used here
ResultRunStringf64fmtfnforimplletmainmutselfstructu32use
The run, in numbers
- Lines
- 26
- Characters to type
- 409
- Tokens
- 134
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 77 seconds.
Step 2 of 4 in Standard traits, step 9 of 19 in Traits & generics.