Convert a String to int in Rust

1. Overview

Converting a string to an integer type is a common task in Rust, especially when working with user input which is primarily text-based.

In this tutorial, we’ll learn how to safely and idiomatically convert from a String to an integer type like i32 using Rust’s built-in parsing capabilities.

2. Using str::parse::<T>() Method

The simplest way to convert from a String to an integer is using the parse() method:

let my_string = "60".to_string(); 
let my_int = my_string.parse::<i32>().unwrap();
assert_eq!(60, my_int);

In the code above, we convert a variable that stores 60 as a String to an integer by invoking the parse() method on the variable. Also, we specify the type to convert to using the turbo fish operator. In case we didn’t specify the type to convert to, Rust uses the default i32 type.

Additionally, the parse() returns a result. This implies that there may be an error and we handle that using the unwrap() method or match.

For example, let’s see an example code that panic:

 let my_string = "Zeus".to_string(); 
let my_int = my_string.parse::<i32>().unwrap();

Here, we’re trying to convert a string to a number. This throws an InvalidDigit error.

Finally, in the case where we are getting the string from a console, it’s advised to trim while parsing to int:

let mut first_number = String::new(); 
io::stdin()
    .read_line(&mut first_number)
    .expect("Failed to read line");

let mut second_number = String::new();
io::stdin()
    .read_line(&mut second_number)
    .expect("Failed to read line");
let parse_first_number = first_number.trim().parse::<i32>().unwrap();
let parse_second_number = second_number.trim().parse::<i32>().unwrap();

let total = parse_first_number + parse_second_number;
print!("{:}", total)

In the code above, we intend to accept two integers and find the sum. The input is treated as string, we convert it to an integer to avoid errors while finding the sum.

However, we invoke trim() method on the input to remove possible whitespaces that can trigger an error while computing the sum.

3. Conclusion

In this tutorial, we learn the simple way to convert a string to an integer in Rust using the parse() method. The method provides easy implementation to convert a string to an integer with proper error handling.