To and from Strings

ToString

To convert any type to a String it is as simple as implementing the ToString
trait for the type.

  1. use std::string::ToString;
  2. struct Circle {
  3. radius: i32
  4. }
  5. impl ToString for Circle {
  6. fn to_string(&self) -> String {
  7. format!("Circle of radius {:?}", self.radius)
  8. }
  9. }
  10. fn main() {
  11. let circle = Circle { radius: 6 };
  12. println!("{}", circle.to_string());
  13. }

Parsing a String

One of the more common types to convert a string into is a number. The idiomatic
approach to this is to use the parse function and provide the type for the
function to parse the string value into, this can be done either without type
inference or using the ‘turbofish’ syntax.

This will convert the string into the type specified so long as the FromStr
trait is implemented for that type. This is implemented for numerous types
within the standard library. To obtain this functionality on a user defined type
simply implement the FromStr trait for that type.

  1. fn main() {
  2. let parsed: i32 = "5".parse().unwrap();
  3. let turbo_parsed = "10".parse::<i32>().unwrap();
  4. let sum = parsed + turbo_parsed;
  5. println!{"Sum: {:?}", sum};
  6. }