ProgrammingRust Developer

How is reading and parsing strings into numbers (for example, from String to i32) implemented in Rust? What pitfalls exist when using the parse method, and how to correctly handle conversion errors?

Pass interviews with Hintsage AI assistant

Answer.

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.

Trick Question.

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();

Examples of real errors due to lack of knowledge of the intricacies of the topic.


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.