Parse integer from string in Rust
August 23, 2022 ‐ 1 min read
In some cases you may receive a numeric value as a string type, for example, a value from stdin
will be given as a string. In such cases you may need to convert the string to an integer before proceeding, for this we may use the str::parse::<T>()
.
let input = "42";
let the_answer = input.parse::<i32>().unwrap();
If the operation fails, meaning that the string could not be parsed into the desired type, an error is thrown. Here we catch the potential error with .unwrap
.
Alternatively we can specify the desired type in the assignment operation.
let input = "42";
let the_answer: i32 = input.parse().unwrap();