Sub topic 7
to_string() for free
This chapter assumes you can write impl Trait for Type, you know println! format strings, and you have implemented Display for a type (previous chapter).
Where to_string() comes from
to_string() is a method of the ToString trait. You almost never implement ToString yourself. The standard library contains this blanket implementation:
impl<T: fmt::Display + ?Sized> ToString for T {
// builds a String by running Display::fmt
}A blanket implementation covers every type that meets a bound. Here the bound is Display. Once your type implements Display, it implements ToString too.
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 describe<T: ToString>(item: &T) -> String {
format!("value = {}", item.to_string())
}
fn main() {
let p = Point { x: 1, y: 2 };
let s: String = p.to_string();
println!("{}", s);
println!("{}", describe(&p));
println!("{}", describe(&42));
}The code does not mention ToString for Point. The method still works, and so does the T: ToString bound in describe. Types such as i32 get the same method because they implement Display.
What to_string() does and does not do
to_string() creates an empty String and calls your Display::fmt with a default Formatter. Two consequences follow.
- It allocates. In hot loops,
write!into an existing buffer orprintln!directly avoids the extraString. - It ignores width, precision, and fill, because the formatter has no options set.
format!("{:>8}", p.to_string())pads the finished string, but that is different from yourDisplayhonoring the options itself.
Common errors
Calling to_string() on a type with only Debug. The compiler reports that the method exists but its trait bounds were not satisfied, because Display is missing. Either implement Display, or format with format!("{:?}", value).
Implementing ToString by hand. This compiles only if the type does not implement Display. Such a type then cannot be used with {}. Implement Display and let the blanket implementation do the rest. Clippy warns about the hand-written version.
Returning Err from Display::fmt. to_string() panics if fmt returns an error that did not come from the underlying writer. Propagate errors from write!, but do not return Err for your own reasons.
Exercise
Exercise
A type Version { major: u32, minor: u32 } derives Debug but does not implement Display. Calling v.to_string() fails to compile. What is the smallest change that makes it print as 1.4?
Show answer
Implement std::fmt::Display for Version with write!(f, "{}.{}", self.major, self.minor). The blanket implementation then provides to_string() automatically, so you do not write a ToString implementation.