Sub topic 7
to_string() for free
This chapter assumes you can write impl Trait for Type, use println! format strings, and have read the previous chapter on implementing Display. It explains why a type that implements Display also gets a to_string() method, and where that method behaves differently from what you might expect.
The method you never wrote
Here is a type with a Display implementation and no other string code.
use std::fmt;
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
let p = Point { x: 1, y: 2 };
let a: String = p.to_string();
let b: String = format!("{}", p);
assert_eq!(a, b);
println!("{}", a);
let points = vec![Point { x: 0, y: 0 }, Point { x: 3, y: -4 }];
let labels: Vec<String> = points.iter().map(ToString::to_string).collect();
println!("{}", labels.join(" -> "));
}The program prints (1, 2) and then (0, 0) -> (3, -4). Nothing in the code defines to_string. It comes from the standard library.
The blanket implementation
The standard library has a trait called ToString with one required method, to_string(&self) -> String. It also contains this implementation:
impl<T: fmt::Display + ?Sized> ToString for T {
// ...
}This is a blanket implementation. It is written for every type T that implements Display, so you never write it yourself. The ?Sized bound lets it apply to unsized types such as str. References to a Display type are also Display, which is why to_string() works on &str, &&str, and &Point.
The method creates an empty String and a Formatter that writes into it. It then calls your Display::fmt and returns the filled string. This is the same work format!("{}", value) does.
What this means in practice
- Any type with
Displaycan be passed to a function bounded byToString. - A type without
Displayhas noto_string(). Calling it gives a compile error saying the method exists but its trait bounds were not satisfied. Vec<T>andOption<T>do not implementDisplay, so they have noto_string(). Use{:?}withformat!for those, if the contents implementDebug.- Integers, floats,
char,bool,str, andStringall implementDisplay, so they all haveto_string().
A generic function can accept anything that can become a string:
fn shout<T: ToString>(value: T) -> String {
value.to_string().to_uppercase()
}
fn main() {
println!("{}", shout("hello"));
println!("{}", shout(42));
println!("{}", shout('x'));
}This prints HELLO, 42, and X. The bound T: std::fmt::Display would work equally well. Prefer Display when you only need to print, because it avoids an allocation. Prefer ToString when you need an owned String.
Do not implement ToString yourself
It can look tidy to implement ToString directly. It does not work, for two reasons.
First, the blanket implementation already covers your type if it has Display. Adding your own ToString then fails with error E0119, conflicting implementations. Second, if your type has no Display, a hand-written ToString compiles but leaves the type unusable in println!("{}", value) and in any Display bound. Clippy warns about this pattern too.
The rule is to implement Display and let to_string() follow.
Where to_string() differs from println!
Allocation
to_string() always allocates a new String. println!("{}", p) writes straight to standard output through your fmt method and builds no intermediate string. In a hot loop that only prints, skip the call:
// Allocates a String, then prints it
println!("{}", p.to_string());
// Writes directly
println!("{}", p);Clippy flags the first form as to_string_in_format_args.
Width and precision are not applied automatically
to_string() uses a default formatter with no width, fill, or precision. Padding specifiers in println! reach your fmt method, but a write! inside it starts a fresh format with default options and drops them. Only f.pad and the formatter's own helper methods honor them. This is a common surprise:
use std::fmt;
struct Plain(&'static str);
struct Padded(&'static str);
impl fmt::Display for Plain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl fmt::Display for Padded {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(self.0)
}
}
fn main() {
println!("[{:>6}]", Plain("ab"));
println!("[{:>6}]", Padded("ab"));
println!("[{}]", Padded("ab").to_string());
}The output is [ab], then [ ab], then [ab]. The third line shows that to_string() never carries width information. If you want padding, apply it where you print: format!("{:>6}", value) or println!("{:>6}", value). A later chapter covers the formatter options in detail.
A failing Display panics
The fmt method returns a fmt::Result. Writing into a String cannot fail, so the standard library treats an Err from your implementation as a bug. to_string() panics with the message "a Display implementation returned an error unexpectedly". Do not return Err(fmt::Error) for domain problems such as invalid data. Return Err only to pass along a failure from the writer, which write!(f, ...)? does for you.
Choosing between the options
| Goal | Use | Allocates |
|---|---|---|
| Print to the terminal | `println!("{}", v)` | No |
| Get an owned string from one value | `v.to_string()` | Yes |
| Build a string from several values | `format!("{} {}", a, b)` | Yes |
| Write into an existing `String` | `write!(s, "{}", v)` with `use std::fmt::Write` | Only if it grows |
| Developer-facing text of a `Debug` type | `format!("{:?}", v)` | Yes |
Common errors
- "the method
to_stringexists but its trait bounds were not satisfied." The type lacksDisplay. ImplementDisplay, or useformat!("{:?}", v)if onlyDebugis available. - Conflicting implementations of trait
ToString. You wroteimpl ToString. Replace it withimpl fmt::Display. - Padding silently ignored. Your
fmtuseswrite!with its own{}. Usef.pad(...)for text that should honor width. - Needless
to_string()inside format macros. Pass the value directly.
Exercise
A teammate writes impl ToString for Version { fn to_string(&self) -> String { format!("v{}", self.0) } } and later adds impl fmt::Display for Version. What happens at compile time, and what is the correct design?
Show answer
The compiler reports a conflicting implementation of ToString (E0119), because the blanket implementation for every T: Display already covers Version. The correct design is to delete the ToString impl and put the logic in Display::fmt, for example write!(f, "v{}", self.0). Then version.to_string() returns the same text.
Exercise
Given struct Id(u32); with impl fmt::Display for Id { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } }, what does println!("[{:>5}]", Id(7)) print, and how would you change fmt so the number is right-aligned in five columns?
Show answer
It prints [7], because write! creates a new format with default options and ignores the width. Replace the body with fmt::Display::fmt(&self.0, f), which passes the formatter on to the inner u32 so it applies the width. The output is then [ 7]. Using f.pad(&self.0.to_string()) also works.