File tree 2 files changed +16
-7
lines changed
2 files changed +16
-7
lines changed Original file line number Diff line number Diff line change 1
1
# To and from Strings
2
2
3
- ## ` ToString `
3
+ ## Converting to String
4
4
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 ] .
7
9
8
10
``` rust,editable
9
- use std::string::ToString ;
11
+ use std::fmt ;
10
12
11
13
struct Circle {
12
14
radius: i32
13
15
}
14
16
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)
18
20
}
19
21
}
20
22
@@ -47,5 +49,7 @@ fn main() {
47
49
```
48
50
49
51
[ `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
50
54
[ `parse` ] : https://doc.rust-lang.org/std/primitive.str.html#method.parse
51
55
[ `FromStr` ] : https://doc.rust-lang.org/std/str/trait.FromStr.html
Original file line number Diff line number Diff line change @@ -67,6 +67,9 @@ friendly fashion.
67
67
Here, ` fmt::Display ` was used because the std library provides implementations
68
68
for these types. To print text for custom types, more steps are required.
69
69
70
+ Implementing the ` fmt::Display ` trait automagically implements the
71
+ [ ` ToString ` ] trait which allows us to [ convert] the type to [ ` String ` ] [ string ] .
72
+
70
73
### Activities
71
74
72
75
* Fix the two issues in the above code (see FIXME) so that it runs without
@@ -87,3 +90,5 @@ and [`traits`][traits]
87
90
[ string ] : std/str.html
88
91
[ structs ] : custom_types/structs.html
89
92
[ traits ] : trait.html
93
+ [ `ToString` ] : https://doc.rust-lang.org/std/string/trait.ToString.html
94
+ [ convert ] : /conversion/string.html
You can’t perform that action at this time.
0 commit comments