typestar

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

  1. #[derive(Debug)] gives you {:?} for free.
  2. Display is hand-written and enables {} and to_string.
  3. {:#?} pretty-prints the derived Debug form.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Standard traits, step 9 of 19 in Traits & generics.

← Previous Next →