w3resource

Rust Program: Extract Some values

Rust Iterators and Iterator Adapters: Exercise-13 with Solution

Write a Rust program that iterates over a vector of Option values and returns a new vector containing only the Some values.

Sample Solution:

Rust Code:

fn main() {
    let options = vec![Some(5), None, Some(10), None, Some(15)];

    // Filter out Some values and collect them into a new vector
    let some_values: Vec<i32> = options
        .clone()                           // Clone the vector to avoid moving it
        .into_iter()                       // Convert the cloned vector into an iterator
        .filter_map(|opt| opt)            // Filter out None values and extract Some values
        .collect();                       // Collect the Some values into a new vector

    println!("Original options: {:?}", options);
    println!("Some values: {:?}", some_values);
}

Output:

Original options: [Some(5), None, Some(10), None, Some(15)]
Some values: [5, 10, 15]

Explanation:

In the exercise above,

  • Start by defining a vector 'options' containing Option values, where some elements are "Some" and others are 'None'.Clone the 'options' vector to avoid moving it. This ensures that we can still use the original vector after iterating over it.Convert the cloned vector into an iterator using "into_iter()", which consumes the vector and produces an iterator over its elements.Using filter_map(|opt| opt), we filter out 'None' values and extract the inner "i32" values from the "Some" variants. This effectively removes the 'None' values from the iterator.Finally, collect the extracted i32 values into a new vector called 'some_values'.Print both the original 'options' vector and the vector containing only the extracted "Some" values (some_values) to observe the filtering operation.

Rust Code Editor:


Previous: Rust Program: Swap Tuple elements.
Next: Rust Program: Calculate differences in Arrays.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/functional-programming/rust-iteretors-and-iterator-adapters-exercise-13.php