]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/conversion/string.md
ab1452153a4758770316f6c25b6d9a65fd1a7f40
[rustc.git] / src / doc / rust-by-example / src / conversion / string.md
1 # To and from Strings
2
3 ## Converting to String
4
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].
9
10 ```rust,editable
11 use std::fmt;
12
13 struct Circle {
14 radius: i32
15 }
16
17 impl fmt::Display for Circle {
18 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
19 write!(f, "Circle of radius {}", self.radius)
20 }
21 }
22
23 fn main() {
24 let circle = Circle { radius: 6 };
25 println!("{}", circle.to_string());
26 }
27 ```
28
29 ## Parsing a String
30
31 One of the more common types to convert a string into is a number. The idiomatic
32 approach to this is to use the [`parse`] function and either to arrange for
33 type inference or to specify the type to parse using the 'turbofish' syntax.
34 Both alternatives are shown in the following example.
35
36 This will convert the string into the type specified so long as the [`FromStr`]
37 trait is implemented for that type. This is implemented for numerous types
38 within the standard library. To obtain this functionality on a user defined type
39 simply implement the [`FromStr`] trait for that type.
40
41 ```rust,editable
42 fn main() {
43 let parsed: i32 = "5".parse().unwrap();
44 let turbo_parsed = "10".parse::<i32>().unwrap();
45
46 let sum = parsed + turbo_parsed;
47 println!("Sum: {:?}", sum);
48 }
49 ```
50
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.md
54 [`parse`]: https://doc.rust-lang.org/std/primitive.str.html#method.parse
55 [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html