w3resource

Rust Function: Filter odd numbers

Rust Result and Option types: Exercise-9 with Solution

Write a Rust function that filters odd numbers from a vector of integers and returns Option<Vec<i32>>, returning None if the input vector is empty.

Sample Solution:

Rust Code:

fn filter_odd_numbers(numbers: Vec<i32>) -> Option<Vec<i32>> {
    // Check if the input vector is empty
    if numbers.is_empty() {
        // If empty, return None
        None
    } else {
        // If not empty, filter odd numbers and return Some containing the result
        Some(numbers.into_iter().filter(|&num| num % 2 != 0).collect())
    }
}

fn main() {
    // Test cases
    let empty_vec: Vec<i32> = Vec::new(); // Empty vector
    let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; // Vector with odd and even numbers

    // Test the filter_odd_numbers function with an empty vector
    match filter_odd_numbers(empty_vec) {
        Some(filtered) => println!("Filtered numbers: {:?}", filtered),
        None => println!("Input vector is empty"),
    }

    // Test the filter_odd_numbers function with a vector containing both odd and even numbers
    match filter_odd_numbers(numbers) {
        Some(filtered) => println!("Filtered numbers: {:?}", filtered),
        None => println!("Input vector is empty"),
    }
}

Output:

Input vector is empty
Filtered numbers: [1, 3, 5, 7, 9]

Explanation:

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

  • The "filter_odd_numbers()" function takes a vector of integers as input and attempts to filter out odd numbers.
  • It first checks if the input vector is empty. If it's empty, the function returns 'None'.
  • If the input vector is not empty, the function filters the odd numbers using "filter()" and "collect()" methods and returns 'Some' containing the filtered result.
  • The "main()" function provides test cases for both scenarios: an empty input vector and a vector containing both odd and even numbers.

Rust Code Editor:

Previous: Rust Function: Safe Division.

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.