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


