Converting a String to int in Rust

Alex Garella image

Alex Garella

8 September 2023

Data conversions are an integral part of programming. If you’re wondering how to convert a String to an int in Rust, you’re in the right place.

Using the parse Method

Rust provides the parse() method, which tries to convert a String to a specified data type.

fn main() {
    let s: String = "42".to_string();
    let number: i32 = s.parse().expect("Not a valid number");
    println!("{}", number);  // Outputs: 42
}

Note: We’ve used expect() for simplicity, but in real-world code, you’d handle the Result more gracefully.

Error Handling with parse

The parse() method returns a Result, which can be an Ok(T) or an Err. To handle potential errors:

fn main() {
    let s = "42a".to_string();
    match s.parse::<i32>() {
        Ok(n) => println!("Number: {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

// Outputs: Error: invalid digit found in string

Conclusion

Converting a String to an int in Rust is straightforward using the parse() method. By leveraging Rust’s powerful error handling mechanism, you ensure safe and predictable conversions.