w3resource

Rust Function: Parse string to integer

Rust Result and Option types: Exercise-1 with Solution

Write a Rust function that returns an Option representing the result of parsing a string into an integer.

Sample Solution:

Rust Code:

fn parse_string_to_integer(input: &str) -> Option<String> {
    match input.parse::<i32>() {
        Ok(parsed_int) => Some(parsed_int.to_string()),
        Err(_) => None,
    }
}

fn main() {
    let input = "150";
    match parse_string_to_integer(input) {
        Some(parsed) => println!("Parsed integer: {}", parsed),
        None => println!("Failed to parse integer"),
    }
}

Output:

Parsed integer: 150

Explanation:

Here's a brief explanation of the above Rust code:

  • 'parse_string_to_integer' takes a string slice 'input' as input and attempts to parse it into an 'i32'.
  • If parsing succeeds ('Ok(parsed_int)'), the function returns 'Some(parsed_int.to_string())', where 'parsed_int' is converted to a string.
  • If parsing fails ('Err(_)'), the function returns 'None'.
  • In the 'main' function, we call 'parse_string_to_integer' with a sample input string '"150"' and handle the result accordingly, printing the parsed integer if successful or a failure message if parsing fails.

Rust Code Editor:

Previous: Rust Result and Option types Exercises.
Next: Rust Function: Find maximum value.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.