To and From String

ToString

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

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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.

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