Skip to content

Commit

Permalink
Merge pull request #1145 from Japanuspus/resolve1131
Browse files Browse the repository at this point in the history
Recommend implementing Display over ToString
  • Loading branch information
marioidival authored Jan 17, 2019
2 parents f2ea341 + 1ee32b3 commit 888e545
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/conversion/string.md
Original file line number Diff line number Diff line change
@@ -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)
}
}
Expand Down Expand Up @@ -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
5 changes: 5 additions & 0 deletions src/hello/print.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

0 comments on commit 888e545

Please sign in to comment.