liveBook · Manning

Display

As explained in Refactoring to Rust

The Display trait is Rust's formatting trait for producing a user-facing textual representation of a value.

A calculator that prints only “Error” leaves users guessing whether an input was invalid or an operation ran out of values. Matching each error wherever it is printed would duplicate messages. Implementing Rust’s Display trait on the error type keeps those messages in one place. section 3.2.3

Display supplies the text used by the {} placeholder in println! and eprintln!. A type implements it by defining fmt, which receives a Formatter and writes to it with write!. The formatter can direct that text to standard output, standard error, or a string. section 3.2.4

Listing 3.11 Display implementation for the Error type
use std::fmt::{Display, Formatter};

enum Error {
  InvalidNumber,
  PopFromEmptyStack,
}

impl Display for Error {
  fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
    match self {
      Error::InvalidNumber => write!(
        f, "Not a valid number or operator"),
      Error::PopFromEmptyStack => write!(
        f, "Tried to operate on empty stack"),
    }
  }
}

The Error implementation matches each variant: an invalid number gets “Not a valid number or operator,” while an empty stack gets “Tried to operate on empty stack.” section 3.2.4

Print the specific error

The calculator’s error branch changes from eprintln!("Error") to eprintln!("Error: {}", e). Entering hello then prints “Error: Not a valid number or operator”; entering 4 * prints “Error: Tried to operate on empty stack.” section 3.2.3 section 3.2.4

How Refactoring to Rust covers it

How deep it goes
Works through fmt, Formatter, write!, variant matching, and the updated error-printing call.
Examples
Uses a hello-world Display implementation and calculator errors for invalid input and an empty stack.
What it assumes
Builds on a calculator returning Result and introduces traits through familiar interfaces and {} printing.
What you can do after
Apply it via std::fmt to define reusable error messages and print them with eprintln!.
How it connects
Connects traits and formatting macros to Result-based error handling and a Rust calculator called through C FFI.

Also explained in

Compare how 3 books explain Display →

Related concepts

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