liveBook · Manning

Display

As explained in Learn Rust in a Month of Lunches

Display printing formats a Rust value using its user-facing Display formatting behavior.

Display printing puts a value into a readable message. In `println!`, `{}` asks Rust to print a value using its `Display` behavior: `println!("Answer: {}", 42)`. Not every type can do this. A trait describes what a type can do, so a type needs the `Display` trait to work with `{}`. section 1.8

When `{}` does not work

Try `println!("This will not print: {}", ());`. The compiler reports that `()` does not implement `Display` and suggests `{:?}` or `{:#?}` instead. Treat that message as a useful hint: use Debug printing when you need to inspect a value that cannot use Display. section 1.8

`{:?}` uses Debug printing, which usually shows more detail and is less polished. `{:#?}` spreads Debug output over more lines when that makes it easier to read. Use `{}` when you want the value’s Display output; use Debug when you want to inspect its structure. section 1.8

use std::fmt;
 
struct Cat {
    name: String,
    age: u8,
}
 
impl fmt::Display for Cat {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
      write!(f, "{} is a cat who is {} years old", self.name, self.age)
  }
}
 
fn main() {
    let mr_mantle = Cat {
        name: "Reggie Mantle".to_string(),
        age: 4,
    };
    println!("{mr_mantle}");
}

This complete example implements `Display` for a `Cat`. Its `fmt` method uses `write!` to choose the sentence that `println!("{mr_mantle}")` prints. section 7.1.1

Deriving `Debug` can print a struct’s fields, but implementing `Display` lets you choose wording suited to the reader. Once a type implements `Display`, it also gains `.to_string()`, which produces a `String` from that formatting. section 7.1.1

A cleaner application screen

An application struct can implement `Display` so its article title, description, and extract appear as a clean screen rather than Debug-style struct output. section 23.3.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Moves from `{}` and compiler feedback to a worked `Display` implementation; leaves some `Formatter` syntax unexplained.
Examples
Uses a failed attempt to print `()`, a custom `Cat` sentence, and cleaner article-application output.
What it assumes
Introduces traits as what a type can do, then uses a struct and trait implementation to customize printing.
What you can do after
Build it from scratch for a struct, then print it with `{}` or turn its output into a `String`.
How it connects
Connects Display to Debug, traits, `write!`, `println!`, and ToString.

Also explained in

Compare how 3 books explain Display →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.