5 To convert any type to a `String` it is as simple as implementing the [`ToString`]
9 use std::string::ToString;
15 impl ToString for Circle {
16 fn to_string(&self) -> String {
17 format!("Circle of radius {:?}", self.radius)
22 let circle = Circle { radius: 6 };
23 println!("{}", circle.to_string());
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.
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.
41 let parsed: i32 = "5".parse().unwrap();
42 let turbo_parsed = "10".parse::<i32>().unwrap();
44 let sum = parsed + turbo_parsed;
45 println!{"Sum: {:?}", sum};
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