Rust Program: Extract Some values
Write a Rust program that iterates over a vector of Option
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.
  
Go to:
PREV : Rust Program: Swap Tuple elements.
NEXT : Rust Program: Calculate differences in Arrays.
Rust Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
