diff --git a/src/conversion/string.md b/src/conversion/string.md index 6073d05a35..82101b8679 100644 --- a/src/conversion/string.md +++ b/src/conversion/string.md @@ -1,20 +1,22 @@ # To and from Strings -## `ToString` +## Converting to String -To convert any type to a `String` it is as simple as implementing the [`ToString`] -trait for the type. +To convert any type to a `String` is as simple as implementing the [`ToString`] +trait for the type. Rather than doing so directly, you should implement the +[`fmt::Display`][Display] trait which automagically provides [`ToString`] and +also allows printing the type as discussed in the section on [`print!`][print]. ```rust,editable -use std::string::ToString; +use std::fmt; struct Circle { radius: i32 } -impl ToString for Circle { - fn to_string(&self) -> String { - format!("Circle of radius {:?}", self.radius) +impl fmt::Display for Circle { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Circle of radius {}", self.radius) } } @@ -47,5 +49,7 @@ fn main() { ``` [`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html +[Display]: https://doc.rust-lang.org/std/fmt/trait.Display.html +[print]: /hello/print.html [`parse`]: https://doc.rust-lang.org/std/primitive.str.html#method.parse [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html diff --git a/src/hello/print.md b/src/hello/print.md index c8e0006d24..e91ee64bcf 100644 --- a/src/hello/print.md +++ b/src/hello/print.md @@ -67,6 +67,9 @@ friendly fashion. Here, `fmt::Display` was used because the std library provides implementations for these types. To print text for custom types, more steps are required. +Implementing the `fmt::Display` trait automagically implements the +[`ToString`] trait which allows us to [convert] the type to [`String`][string]. + ### Activities * Fix the two issues in the above code (see FIXME) so that it runs without @@ -87,3 +90,5 @@ and [`traits`][traits] [string]: std/str.html [structs]: custom_types/structs.html [traits]: trait.html +[`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html +[convert]: /conversion/string.html