skip to content

When a derived `Debug` is wrong for a Rust `Matrix`, how do `debug_struct`, `debug_list` and `finish_non_exhaustive` keep both `{:?}` and `{:#?}` working?

level: seniorimportance: nice to knowfreq 25%

answer

  1. builders own the punctuation
  2. the alternate flag decides layout
  3. two dots for hidden fields
  4. a closure that implements Debug

basics

~10 s

Formatter's debug builders write the braces, commas and indentation themselves and switch to multi-line output when the alternate flag is set, so {:#?} keeps working. finish_non_exhaustive prints .. to mark fields deliberately left out.

solid answer

~40 s

A hand-written `impl fmt::Debug` should use `f.debug_struct("Matrix").field(..)`, `debug_list().entries(..)` and the tuple, set and map builders rather than `write!`. The builders read `f.alternate()` themselves: compact on `{:?}`, one indented entry per line on `{:#?}`, and they pass the caller's `Formatter` on to field values. Ending with `finish_non_exhaustive()` (stable on `DebugStruct` since 1.53, on the other builders since 1.83) prints `..` for omitted fields such as a cache or a secret. For layout control, `std::fmt::from_fn` (Rust 1.93) turns a closure into a `Debug` value, so each matrix row can print compactly while `{:#?}` puts one row per line. A plain `write!` impl prints the same single line for both placeholders.

code

rust · 29 lines
rust
use std::fmt;

struct Matrix {
    cols: usize,
    data: Vec<f64>,  // row-major
    cache_hits: u64, // bookkeeping a reader of the dump does not need
}

impl fmt::Debug for Matrix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Each row prints compactly, even when the caller asked for {:#?}.
        let rows: Vec<_> = self
            .data
            .chunks(self.cols)
            .map(|row| fmt::from_fn(move |f| write!(f, "{row:?}")))
            .collect();
        f.debug_struct("Matrix")
            .field("cols", &self.cols)
            .field("rows", &rows)
            .finish_non_exhaustive() // prints `..` for the skipped cache_hits
    }
}

fn main() {
    let m = Matrix { cols: 3, data: vec![1.0, 0.0, 2.5, 0.0, 1.0, -1.0], cache_hits: 7 };
    assert_eq!(m.cache_hits, 7);
    println!("{m:?}");
    println!("{m:#?}");
}

go deeper

for a junior

Recall that a manual Debug impl should use f.debug_struct and .field rather than write!, and that {:#?} is the pretty form of the same impl.

for a middle

Explain how the builders read the alternate flag and pass the Formatter to each field, and what finish_non_exhaustive prints for omitted fields.

for a senior

Shape Debug output for large or sensitive types: hide secrets and bookkeeping with finish_non_exhaustive, and control line breaks with fmt::from_fn or a wrapper type so logs stay readable.

for a principal

Set the rule that Debug on types holding credentials is hand-written with finish_non_exhaustive, and that Debug output is never parsed, so its layout can change freely.

## When the derived `Debug` is the wrong dump `#[derive(Debug)]` prints every field in declaration order. For a `Matrix { cols: usize, data: Vec<f64>, cache_hits: u64 }` that is unhelpful twice over: - `data` is a flat row-major vector, so a 3×3 matrix prints as nine numbers in one list with no row boundaries; - `cache_hits` is internal bookkeeping that clutters every log line; - under `{:#?}`, the derived output puts **every number on its own line**, so a 10×10 matrix becomes over a hundred lines. The answer is a hand-written `impl fmt::Debug`. The question is how to write one that still behaves like a derived one. ## Why not just `write!` A `Debug` impl written as `write!(f, "Matrix {{ cols: {} }}", self.cols)` works for `{:?}`, but it has hand-made the punctuation, so: - `{:#?}` prints exactly the same single line — the alternate flag is ignored, because nothing in the impl reads `f.alternate()`; - nested values formatted inside it lose the indentation the caller expected; - the output stops looking like every other `Debug` dump in the log. ## The `Formatter` builders `std::fmt::Formatter` offers builder methods that produce the same shapes the derive does, and handle both modes for you: | Method | Shape | Typical use | |---|---|---| | `debug_struct(name)` + `.field(name, &value)` | `Name { a: 1, b: 2 }` | structs with named fields | | `debug_tuple(name)` + `.field(&value)` | `Name(1, 2)` | tuple structs and enum variants | | `debug_list()` + `.entry` / `.entries` | `[1, 2]` | sequences | | `debug_set()` | `{1, 2}` | sets | | `debug_map()` + `.entry(&k, &v)` / `.key` / `.value` | `{k: v}` | maps | Each builder checks the **alternate flag** itself: in `{:?}` mode it writes commas and spaces on one line, in `{:#?}` mode it writes one entry per line with indentation and a trailing comma, and it passes the caller's `Formatter` on to the field values. The impl ends with `.finish()`. ## Saying "there is more" with `finish_non_exhaustive` When fields are deliberately left out, end the builder with `finish_non_exhaustive()` instead of `finish()`. It prints `..` after the fields that were shown: - `Matrix { cols: 3, rows: [...], .. }` in compact mode; - a final `..` line in pretty mode. `DebugStruct::finish_non_exhaustive` has been stable since Rust 1.53; the same method on `DebugTuple`, `DebugList`, `DebugSet` and `DebugMap` arrived in Rust 1.83. It is also the idiomatic way to keep secrets — a token, a password hash — out of logs without pretending the field does not exist. ## Controlling granularity with `fmt::from_fn` To print the matrix **one row per line** under `{:#?}`, each row should be a single compact entry. Since Rust 1.93, `std::fmt::from_fn` wraps a closure into a value whose `Debug` and `Display` call that closure. The steps are: 1. split `data` into rows with `chunks(self.cols)`; 2. map each row to `fmt::from_fn(move |f| write!(f, "{row:?}"))` — the inner `write!` uses fresh, compact formatting; 3. pass the collected rows to `.field("rows", &rows)`, so the list builder puts each row on its own line in pretty mode; 4. finish with `finish_non_exhaustive()` to mark the hidden `cache_hits`. The program in this question prints `Matrix { cols: 3, rows: [[1.0, 0.0, 2.5], [0.0, 1.0, -1.0]], .. }` for `{:?}` and an eight-line block with one matrix row per line for `{:#?}`. Before 1.93 the same effect was usually achieved with a small private wrapper struct carrying its own `Debug` impl. ## Pitfalls - Using `write!` for the whole impl and losing `{:#?}`. - Calling `finish()` after dropping fields, so readers assume the dump is complete. - Formatting rows with `format!` into `String`s and passing those: a `String`'s `Debug` adds quotes and escapes. - Treating the hand-written layout as stable — like derived output, `Debug` text is for people, not for parsers.

  • How do you keep an API token field out of a Rust type's `Debug` output without hiding that it exists?
    Write `Debug` by hand with `f.debug_struct("Client")`, add only the safe fields, and end with `finish_non_exhaustive()`, which prints `..`. Alternatively add `.field("token", &"<redacted>")`. Both keep `{:#?}` working; a derived `Debug` would print the token.
  • Why not format each matrix row into a `String` and pass the strings to `debug_list`?
    A `String`'s own `Debug` adds quotes and escapes, so each row would print as `"[1.0, 0.0, 2.5]"`. Wrapping the row in `fmt::from_fn` (Rust 1.93) or a small wrapper type with its own `Debug` writes the text without quotes.

  • A write!-based Debug impl automatically becomes multi-line under {:#?}.
  • finish() is fine after skipping fields; readers know the dump is partial.
  • finish_non_exhaustive has been on every debug builder since Rust 1.0.
  • Passing pre-formatted Strings to debug_list prints the rows without quotes.
  • Pretty-printing requires a separate PrettyDebug implementation.

Assumes Rust 1.99; DebugStruct::finish_non_exhaustive is stable since 1.53, the other builders' finish_non_exhaustive since 1.83, and std::fmt::from_fn since 1.93.