Rust function for modifying Option values
Rust Closures and Higher-Order Functions: Exercise-14 with Solution
Write a Rust function that takes a closure and a vector of values, applies the closure to each Some value, and returns a new vector of modified Option values.
Sample Solution:
Rust Code:
fn apply_closure_to_option<T, U, F>(vect: Vec<Option<T>>, mut closure: F) -> Vec<Option<U>>
where
F: FnMut(T) -> U, // Change to FnMut trait
{
vect
.into_iter() // Convert the input vector into an iterator
.map(|opt| opt.map(|x| closure(x))) // Apply the closure to each Some value
.collect() // Collect the modified Option values into a new vector
}
fn main() {
let vect = vec![Some(5), None, Some(10), Some(15)];
println!("Original options: {:?}", vect);
// Example usage: Double the Some values
let modified_temps = apply_closure_to_option(vect, |x| x * 2);
println!("Modified options: {:?}", modified_temps);
}
Output:
Original options: [Some(5), None, Some(10), Some(15)] Modified options: [Some(10), None, Some(20), Some(30)]
Explanation:
In the exercise above,
- apply_closure_to_option function:
- Generic function that takes three type parameters: 'T', 'U', and 'F'.
- It accepts a vector of Option
values (vect) and a closure (closure) that takes a value of type 'T' and returns a value of type 'U'. - The closure must implement the 'FnMut' trait, allowing it to mutate in its environment.
- It converts the input vector into an iterator using "into_iter()".
- Using "map", it applies the closure to each "Some" value in the vector, mapping each "Some" value to the result of applying the closure to its inner value. "map" preserves 'None' values.
- Finally, it collects the modified 'Option' values into a new vector using "collect()" and returns it.
- main function:
- It initializes a vector 'vect' containing "Some" and 'None' values.
- Calls "apply_closure_to_option()" with 'vect' and a closure that doubles the value of each "Some" variant.
- Prints the original and modified vectors.
Rust Code Editor:
Previous: Rust Higher-Order function for Tuple modification.
Next: Rust function for modifying Arrays element-wise.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-closures-and-higher-order-functions-exercise-14.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics