w3resource

Modify vector elements with Rust Closure function

Rust Closures and Higher-Order Functions: Exercise-3 with Solution

Write a Rust function that iterates over a vector of integers and applies a closure to each element, modifying the original vector.

Sample Solution:

Rust Code:

fn apply_closure_to_vector<F>(vector: &mut Vec<i32>, mut closure: F)
where
    F: FnMut(&mut i32), // Define the closure trait bound
{
    for num in vector.iter_mut() { // Iterate over each element in the vector
        closure(num); // Apply the closure to the current element
    }
}

fn main() {
    let mut numbers = vec![100, 200, 300, 400, 500]; // Define a vector of integers
    println!("Original vector: {:?}", numbers); // Print the original vector
    
    // Define a mutable closure that adds one to each element
    let mut add_one = |x: &mut i32| *x += 1;
    
    // Apply the closure to each element of the vector
    apply_closure_to_vector(&mut numbers, &mut add_one);
    
    // Print the modified vector
    println!("Modified vector: {:?}", numbers);
}

Output:

Original vector: [100, 200, 300, 400, 500]
Modified vector: [101, 201, 301, 401, 501]

Explanation:

In the exercise above,

  • The "apply_closure_to_vector()" function:
    • This function takes two parameters: a mutable reference to a vector of integers (vector: &mut Vec<i32>) and a mutable closure (closure: F) where 'F' is a generic type that represents any closure that takes a mutable reference to an 'i32'.
    • Inside the function, it iterates over each element of the vector using "iter_mut()", which allows mutable access to each element.
    • For each element, it applies the closure "closure" by invoking it with the current element as an argument (closure(num)).
  • The main function:
    • It initializes a vector of integers "numbers" with values [100, 200, 300, 400, 500].
    • It defines a closure "add_one" using the |parameter| { body } syntax. This closure takes a mutable reference to an 'i32' and increments the value by 1 (*x += 1).
    • It calls the "apply_closure_to_vector()" function with a mutable reference to 'numbers' and the closure "add_one".
    • After applying the closure to each element of the vector, it prints the modified vector.

Rust Code Editor:


Previous: Applying Closure to two numbers in Rust.
Next: With Rust Higher-Order Filter integers function.

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-closures-and-higher-order-functions-exercise-3.php