Why does Rust's standard library tell you to implement `Display` rather than `ToString`, and what does `money.to_string()` actually call?
answer
- a trait you get for free
- impl for every T: Display
- conflicting implementations
- default options, panic on Err
basics
~20 sstd has a blanket impl<T: Display + ?Sized> ToString for T, so implementing Display gives to_string() for free. A hand-written ToString on a Display type conflicts with it (E0119), and ToString alone cannot be used with {}.
solid answer
~30 s`to_string()` comes from a blanket impl in std, `impl<T: fmt::Display + ?Sized> ToString for T`. It creates an empty `String` and a `Formatter` with default options, calls your `Display::fmt` once and returns the buffer, panicking with "a Display implementation returned an error unexpectedly" if `fmt` returns `Err`. So `money.to_string()` equals `format!("{money}")`, never the padded text of `{money:>14}`. The `ToString` docs say it shouldn't be implemented directly: writing `impl ToString for Money` next to a `Display` impl fails with E0119, conflicting implementations, and implementing only `ToString` leaves the type unusable with `{}`, `write!` and padding.
code
plaintext · 9 lineserror[E0119]: conflicting implementations of trait `ToString` for type `Money`
--> g.rs:6:1
|
6 | impl ToString for Money {
| ^^^^^^^^^^^^^^^^^^^^^^^
|
= note: conflicting implementation in crate `alloc`:
- impl<T> ToString for T
where T: std::fmt::Display, T: ?Sized;go deeper
Recall that implementing Display is enough to get to_string(), and that you never write impl ToString yourself.
Explain the blanket impl over T: Display + ?Sized, why a direct impl hits E0119, and that to_string uses default formatting options.
Know that a Display impl returning its own Err makes to_string panic, and prefer write! into an existing buffer over to_string in hot paths.
Set the API rule that public types expose Display, not ToString, and that functions which only print a value accept impl Display instead of a pre-built String.
## Where `to_string()` comes from `ToString` is a one-method trait in `alloc::string`, re-exported as `std::string::ToString` and in the prelude: ```rust pub trait ToString { fn to_string(&self) -> String; } ``` Right below it, std provides a **blanket implementation**: ```rust impl<T: fmt::Display + ?Sized> ToString for T { /* ... */ } ``` Every type that implements `Display` — including unsized ones such as `str`, thanks to `?Sized` — therefore implements `ToString` automatically. When you write `impl fmt::Display for Money`, `price.to_string()` starts working with no further code. The general rules about blanket impls and coherence are a topic of their own; what matters here is what this particular impl does. ## Why the docs say "implement `Display`, not `ToString`" The `ToString` documentation is explicit: it "is automatically implemented for any type which implements the `Display` trait. As such, `ToString` shouldn't be implemented directly: `Display` should be implemented instead, and you get the `ToString` implementation for free." The `Display` docs repeat the advice. There are three concrete reasons: 1. **A direct impl collides with the blanket one.** If `Money` implements both `Display` and `ToString`, rustc 1.99 rejects the second with E0119, "conflicting implementations of trait `ToString` for type `Money`", pointing at `impl<T> ToString for T where T: std::fmt::Display`. 2. **`ToString` alone is a dead end.** A type that implements only `ToString` compiles, but it cannot be used with `{}` in `format!`, `println!` or `write!`, cannot be padded or aligned, and cannot be written into a `Formatter` or an `io::Write` without first allocating a `String`. 3. **`Display` writes into any sink.** `Display::fmt` streams into whatever the `Formatter` wraps — a `String`, a buffered writer, a log line — while `to_string()` always allocates a fresh `String`. ## What the blanket impl actually does Reading `alloc/src/string.rs` in Rust 1.99, the generic path: - creates an empty `String` and a `Formatter` with **default options** — no width, no precision, no flags; - calls your `Display::fmt` once; - **panics** with "a Display implementation returned an error unexpectedly" if `fmt` returns `Err`. Two consequences follow: - `price.to_string()` produces the same text as `format!("{price}")`, but never the padded text of `format!("{price:>14}")`. - A `Display` impl that returns `Err(fmt::Error)` on its own — say, because a value is "invalid" — turns every `to_string()` call into a panic. The impl block's doc comment explains why: `fmt::Write for String` never returns an error itself, so an error can only come from a broken `Display`. Internally std routes the call through a private helper that has faster paths for some types (`char`, `bool`, integer types, `fmt::Arguments` and others). That helper uses the unstable `specialization` feature inside std only; it is not something your crate can do on stable Rust, and it does not change the text produced. ## What it costs Every `to_string()` call allocates a new `String`, and for a user type it also runs the whole formatting path once: - the buffer starts empty and grows as `Display::fmt` writes, so a long value may reallocate a few times; - for `str`, `&str`, `String` and `Cow<str>`, std skips formatting and copies the bytes straight into a new `String` with `String::from`; - integer types and `char`, `bool` and `fmt::Arguments` also have dedicated paths in std, again with the same text as the generic one. None of this changes what your own type does: it always goes through the generic path and your `Display::fmt`. When many values end up in one buffer, write them with `write!` into that buffer instead of concatenating `to_string()` results. ## `to_string()` compared with the alternatives | Expression | Needs | Result | |---|---|---| | `price.to_string()` | `Display` | a new `String`, default formatting | | `format!("{price}")` | `Display` | the same text as `to_string()` | | `format!("{price:>14}")` | `Display` that honours width | padded text | | `format!("{price:?}")` | `Debug` | the developer view, not the user view | | `write!(out, "{price}")` | `Display` | streams into `out`, no intermediate `String` | ## Practical guidance - Implement `Display` and let the blanket impl supply `to_string()`; never write `impl ToString`. - Prefer `write!` into an existing buffer in hot loops instead of collecting `to_string()` results. - Keep `Display::fmt` infallible apart from propagating the formatter's own errors, so `to_string()` cannot panic. - In APIs, accept `impl Display` (or `&dyn Display`) when you only need to print a value, rather than forcing callers to allocate a `String` first.
- What happens when a Rust `Display::fmt` returns `Err(fmt::Error)` on its own and someone calls `to_string()`?The blanket impl panics with "a Display implementation returned an error unexpectedly". Its doc comment calls this an incorrect `Display` implementation, because writing into a `String` never fails; `fmt` should only propagate errors the `Formatter` itself returns.
- Does `price.to_string()` honour a width or precision in Rust?No. It formats with default options — no width, no precision, no flags — so it matches `format!("{price}")`. For padded text use `format!("{price:>14}")`, and make sure the `Display` impl honours the width.
- Implement ToString yourself so the type gets a to_string method.
- to_string applies the same width and precision as the surrounding format string.
- A type implementing only ToString can be printed with {} in println!.
- Display::fmt may return Err to signal an invalid value, and to_string returns empty.