convert a string to an integer in rust

You can convert a string to an integer in Rust using the parse method. Here's an example:

main.rs
let my_string = "42";
let my_int = my_string.parse::<i32>().unwrap();
70 chars
3 lines

In the code above, we define a my_string variable and assign it the value "42". We then use the parse method to convert my_string to an integer by specifying the integer type using the ::<i32>() syntax. Finally, we use the unwrap method to extract the integer value from the Result object returned by parse.

Alternatively, if you don't want to use unwrap, you can use a match statement to handle the Result object:

main.rs
let my_string = "42";
let my_int_result = my_string.parse::<i32>();
let my_int = match my_int_result {
    Ok(num) => num,
    Err(_) => {
        println!("Failed to convert string to int");
        0
    },
};
212 chars
10 lines

In this version of the code, we use the match statement to handle the Result object. If the result is Ok, we extract the integer value; otherwise, we print an error message and return 0.

gistlibby LogSnag