Skip to content

Commit 888e545

Browse files
authored
Merge pull request #1145 from Japanuspus/resolve1131
Recommend implementing Display over ToString
2 parents f2ea341 + 1ee32b3 commit 888e545

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

src/conversion/string.md

+11-7
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,22 @@
11
# To and from Strings
22

3-
## `ToString`
3+
## Converting to String
44

5-
To convert any type to a `String` it is as simple as implementing the [`ToString`]
6-
trait for the type.
5+
To convert any type to a `String` is as simple as implementing the [`ToString`]
6+
trait for the type. Rather than doing so directly, you should implement the
7+
[`fmt::Display`][Display] trait which automagically provides [`ToString`] and
8+
also allows printing the type as discussed in the section on [`print!`][print].
79

810
```rust,editable
9-
use std::string::ToString;
11+
use std::fmt;
1012
1113
struct Circle {
1214
radius: i32
1315
}
1416
15-
impl ToString for Circle {
16-
fn to_string(&self) -> String {
17-
format!("Circle of radius {:?}", self.radius)
17+
impl fmt::Display for Circle {
18+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
19+
write!(f, "Circle of radius {}", self.radius)
1820
}
1921
}
2022
@@ -47,5 +49,7 @@ fn main() {
4749
```
4850

4951
[`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html
52+
[Display]: https://doc.rust-lang.org/std/fmt/trait.Display.html
53+
[print]: /hello/print.html
5054
[`parse`]: https://doc.rust-lang.org/std/primitive.str.html#method.parse
5155
[`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html

src/hello/print.md

+5
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ friendly fashion.
6767
Here, `fmt::Display` was used because the std library provides implementations
6868
for these types. To print text for custom types, more steps are required.
6969

70+
Implementing the `fmt::Display` trait automagically implements the
71+
[`ToString`] trait which allows us to [convert] the type to [`String`][string].
72+
7073
### Activities
7174

7275
* Fix the two issues in the above code (see FIXME) so that it runs without
@@ -87,3 +90,5 @@ and [`traits`][traits]
8790
[string]: std/str.html
8891
[structs]: custom_types/structs.html
8992
[traits]: trait.html
93+
[`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html
94+
[convert]: /conversion/string.html

0 commit comments

Comments
 (0)