Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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