OneBite.Dev - Coding blog in a bite size

Convert Variable From String To Int In Rust

Code snippet for how to Convert Variable From String To Int In Rust with sample and detail explanation

Learning the Rust programming language can open up a whole new world of system programming, concurrent programming, and safe software development. One of the common tasks you may need to perform is converting variables from a String to an Integer. In this simple article, we’ll take a closer look at how this can be accomplished.

Code snippet: Convert Variable from String to Int in Rust

Here’s the code snippet showing how to convert a string to an integer in Rust:

fn main() {
    let example_string = "123";
    let converted_num = example_string.parse::<i32>().unwrap();
    println!("The integer is: {}", converted_num);
}

Code Explanation for: Convert Variable from String to Int in Rust

Firstly, we start by invoking the main() function, which is where our program starts execution.

fn main() {

Then, we define a string variable called example_string with the value of “123”.

    let example_string = "123";

Rust allows type annotations to be added to expressions with turbofish syntax. Therefore, by using the parse::<i32>() method, we tell Rust to parse this string and convert it into an integer.

In addition, we need to handle potential errors that might occur during the parsing process because not all strings can be converted into a number. As this is a simple snippet, we employ the .unwrap() method that gives the program permission to panic and crash if there’s any error during parsing.

    let converted_num = example_string.parse::<i32>().unwrap();

Lastly, we use the println!("The integer is: {}", converted_num); line of code to print out the result.

    println!("The integer is: {}", converted_num);
}

And that’s it! We have successfully converted a string to an integer in Rust using the parse method. Always remember, While the .unwrap() function is okay to use in small scripts and tests, for larger software, you would want to use proper error handling.

rust