In Rust, the standard method for converting a string to a number is the parse() method. It can be applied to types that implement the FromStr trait, for example, to convert String or &str to i32, f64, and others.
Example:
let num: i32 = "42".parse().unwrap();
However, with an incorrect string, an error arises (Result::Err). It is important to handle the result using match to avoid application crash:
let input = "abc"; match input.parse::<i32>() { Ok(n) => println!("Number: {}", n), Err(e) => println!("Parsing error: {}", e), }
The parse method supports type overloading through "turbofish" (::<i32>), if the type cannot be inferred implicitly.
Question: Can you call .parse() without specifying the type at compile time and get a correct result?
Common Answer: Yes, if the string contains a number.
Correct Answer: No, the type to which the conversion is made must be known at compile time. If the type cannot be inferred (for example, it is not used explicitly later), the compiler will emit an error.
Example of incorrect code:
let x = "10".parse(); // Error: unclear which type to parse to
To fix, use turbofish:
let x = "10".parse::<i32>().unwrap();
Story
In the config parsing module, they left .parse().unwrap() without error handling. A typo in user settings led to panic! and stopped the entire application in production.
Story
In one project, the developers did not specify the type explicitly (did not use turbofish), and the variable was not used in-between, so the compiler could not infer the type, leading to a hard-to-trace error at compile time.
Story
A bug occurred in the project because they accidentally applied parse::<u8> for parsing a large number from a string, which led to overflow error. The error was discovered only after several weeks of usage when data was lost.