]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/conversion/string.md
New upstream version 1.27.1+dfsg1
[rustc.git] / src / doc / rust-by-example / src / conversion / string.md
1 # To and from Strings
2
3 ## `ToString`
4
5 To convert any type to a `String` it is as simple as implementing the [`ToString`]
6 trait for the type.
7
8 ```rust,editable
9 use std::string::ToString;
10
11 struct Circle {
12 radius: i32
13 }
14
15 impl ToString for Circle {
16 fn to_string(&self) -> String {
17 format!("Circle of radius {:?}", self.radius)
18 }
19 }
20
21 fn main() {
22 let circle = Circle { radius: 6 };
23 println!("{}", circle.to_string());
24 }
25 ```
26
27 ## Parsing a String
28
29 One of the more common types to convert a string into is a number. The idiomatic
30 approach to this is to use the [`parse`] function and provide the type for the
31 function to parse the string value into, this can be done either without type
32 inference or using the 'turbofish' syntax.
33
34 This will convert the string into the type specified so long as the [`FromStr`]
35 trait is implemented for that type. This is implemented for numerous types
36 within the standard library. To obtain this functionality on a user defined type
37 simply implement the [`FromStr`] trait for that type.
38
39 ```rust
40 fn main() {
41 let parsed: i32 = "5".parse().unwrap();
42 let turbo_parsed = "10".parse::<i32>().unwrap();
43
44 let sum = parsed + turbo_parsed;
45 println!{"Sum: {:?}", sum};
46 }
47 ```
48
49 [`ToString`]: https://doc.rust-lang.org/std/string/trait.ToString.html
50 [`parse`]: https://doc.rust-lang.org/std/primitive.str.html#method.parse
51 [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html