skip to content

In Rust, why can a `Money` struct use `#[derive(Debug)]` while its `Display` implementation must be written by hand?

level: juniorimportance: must knowfreq 80%

answer

  1. two audiences, two traits
  2. developer view vs user view
  3. derive walks the fields
  4. formatting decisions fields cannot encode

basics

~20 s

Debug is the developer view, which rustc can generate mechanically from the type name and every field. Display is the user-facing text, a design choice only the author can make, so std ships no derive for it.

solid answer

~40 s

`{:?}` calls `fmt::Debug` and `{}` calls `fmt::Display`. `#[derive(Debug)]` generates an impl that prints the struct name and each field's name with its own `Debug` value, and `{:#?}` pretty-prints the same impl across indented lines; it needs every field to be `Debug` and adds a `T: Debug` bound per type parameter. `Display` has no derive in std — its docs say it is for user-facing output and so cannot be derived — because how a `Money` should read (`19.99 EUR`, which fields to hide) is not visible in the fields. So you derive `Debug` almost everywhere and hand-write `impl fmt::Display` where people read the value. Using `{}` on a type without `Display` is a compile error, E0277, never a fallback to `Debug`.

code

rust · 23 lines
rust
use std::fmt;

#[derive(Debug)] // developer view: generated from the fields
struct Money {
    cents: i64,
    currency: &'static str,
}

// User view: written by hand, because only you know how money should read.
impl fmt::Display for Money {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sign = if self.cents < 0 { "-" } else { "" };
        let abs = self.cents.unsigned_abs();
        write!(f, "{sign}{}.{:02} {}", abs / 100, abs % 100, self.currency)
    }
}

fn main() {
    let price = Money { cents: 1999, currency: "EUR" };
    println!("{price}");   // Display
    println!("{price:?}"); // Debug
    println!("{price:#?}"); // pretty Debug
}

go deeper

for a junior

Recall the pairing: {} calls Display, {:?} and {:#?} call Debug. Derive Debug on your types and write Display by hand with write! when users see the value.

for a middle

Explain what the Debug derive generates field by field, the T: Debug bound it adds on generics, and why a missing trait is a compile-time E0277 rather than a runtime fallback.

for a senior

Show that you keep the two views apart in production: Debug on every public type for logs and test failures, Display only where it is a deliberate user-facing format, with secrets kept out of both.

for a principal

Frame Display as a contract users may come to depend on and Debug as unstable diagnostics, so a team documents its Display formats and never lets tooling parse Debug output.

## Two traits, two audiences Rust's formatting machinery (`format!`, `println!`, `write!` and friends) picks a **formatting trait** from the placeholder you write. The two you meet first are `std::fmt::Display` and `std::fmt::Debug`: | Placeholder | Trait called | Audience | Can it be derived? | |---|---|---|---| | `{}` | `fmt::Display` | the end user reading a screen, a receipt or a CLI line | no — written by hand | | `{:?}` | `fmt::Debug` | the developer reading a log line, a test failure or a debugger dump | yes — `#[derive(Debug)]` | | `{:#?}` | `fmt::Debug` with the alternate flag | the developer, pretty-printed across indented lines | same impl as `{:?}` | The choice is made **at compile time**. The macro expands to code that calls exactly the trait the placeholder names, so there is no runtime fallback from one to the other. ## What `#[derive(Debug)]` generates `Debug` is a **mechanical** view: it shows what the value is made of. That is why rustc can write it for you. For a struct, the derived impl prints: - the struct's name, then `{`; - each field's name followed by that field's own `Debug` output, comma-separated; - a closing `}` — or, for an enum, the variant name with its fields in parentheses or braces. Three consequences follow from that design: - **Every field must implement `Debug`**, or the derive fails with E0277 on the offending field. - On a generic type the derive adds a bound per type parameter, so `struct Wrapper<T>` gets `impl<T: Debug> Debug for Wrapper<T>`. - The standard library documents that **derived `Debug` formats are not stable** and may change between Rust versions, and so may the `Debug` output of std's own types. Treat `{:?}` text as diagnostic, never as an interface to parse or to show customers. ## Why `Display` has no derive The `Display` documentation states it plainly: `Display` is for user-facing output, "and so cannot be derived". Writing `#[derive(Display)]` is rejected with "cannot find derive macro `Display` in this scope", and rustc adds that `Display` is a trait, not a derive macro. The reason is that user-facing text is a set of **decisions** the fields do not encode. For a `Money { cents: i64, currency: &'static str }` you have to decide: 1. whether to print `19.99 EUR`, `EUR 19.99` or `€19.99`; 2. how many decimal places to show and how to place a minus sign; 3. which fields to hide entirely — an internal id, a cache, a secret; 4. whether the output should round-trip through `FromStr`. None of these can be read off a field list, so std leaves `Display` to you. Crates outside std offer derive macros for it, but someone still has to decide the format — the design work does not go away. ## Writing `Display` for `Money` An implementation has one method, `fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result`. The usual body is a `write!` into the formatter: ```rust impl fmt::Display for Money { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let abs = self.cents.unsigned_abs(); let sign = if self.cents < 0 { "-" } else { "" }; write!(f, "{sign}{}.{:02} {}", abs / 100, abs % 100, self.currency) } } ``` Return the `fmt::Result` you get from `write!`; never invent an error of your own, because formatting into memory is meant to be infallible. ## When one of them is missing Printing a `Money` that only derives `Debug` with `{}` does not compile. rustc 1.99 reports E0277, "`Money` doesn't implement `std::fmt::Display`", labels the placeholder "`Money` cannot be formatted with the default formatter", and notes that `{:?}` (or `{:#?}` for pretty-print) may be what you meant. The mirror case — `{:?}` on a type with no `Debug` — is also E0277, with a suggestion to add `#[derive(Debug)]`. ## Rules of thumb - Derive `Debug` on practically every type you define; the Rust API Guidelines list "All public types implement `Debug`" and say exceptions are rare. - Implement `Display` only for types an end user, a CLI or a message shown to people actually reads. - Keep the two different: `Debug` can show every field, `Display` shows only what the reader needs. - Remember that implementing `Display` also gives the type `to_string()` through a blanket impl in std.

  • Does `{}` fall back to `Debug` when a Rust type has no `Display` implementation?
    No. The placeholder chooses the trait at compile time, so `println!("{m}")` on a type without `Display` fails with E0277, "`Money` doesn't implement `std::fmt::Display`". rustc's note suggests `{:?}` or `{:#?}`, but switching is your decision, not an automatic fallback.
  • Can a test assert on the exact text of a derived `Debug` output?
    It can, but it should not rely on it long term: the `Debug` docs say derived `Debug` formats are not stable and may change with future Rust versions, and the same holds for std types' `Debug` output. Assert on fields, or on a `Display` format you own and document.
  • What does `#[derive(Debug)]` generate for a generic `struct Wrapper<T> { inner: T }`?
    An `impl<T: Debug> Debug for Wrapper<T>`: the derive adds a `Debug` bound on each type parameter. So `Wrapper<i32>` is `Debug`, while a `Wrapper` around a type that lacks `Debug` simply has no `Debug` impl, and printing it with `{:?}` fails with E0277.

Debug is the inspection sticker inside a machine's panel, listing every part for the technician; Display is the price tag on the shelf, and someone has to decide what the customer sees.

  • Printing with {} falls back to the derived Debug output when Display is missing.
  • You can write #[derive(Display)] just like #[derive(Debug)] using std alone.
  • Derived Debug text is a stable format you can parse or show to customers.
  • Implementing Display automatically gives a type a Debug implementation too.
  • Pretty-printing with {:#?} needs its own trait or derive beyond Debug.