w3resource

Apply Closure to range in Rust

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

Write a Rust program that creates a higher-order function that takes a closure and a range of numbers, and applies the closure to each number in the range, returning a new vector of results.

Sample Solution:

Rust Code:

fn apply_closure_to_range<F>(range: std::ops::Range<i32>, closure: F) -> Vec<i32>
where
    F: Fn(i32) -> i32, // Closure trait bound
{
    range.into_iter() // Convert the input range into an iterator
        .map(closure) // Apply the closure to each number in the range and collect the results
        .collect() // Collect the modified numbers into a new vector
}

fn main() {
    // Example usage:
    let range = 1..6; // Range from 1 to 5 (inclusive)
    let modified_numbers = apply_closure_to_range(range, |x| x * 3);
    println!("Modified numbers: {:?}", modified_numbers);
}

Output:

Modified numbers: [3, 6, 9, 12, 15]

Explanation:

The above code defines a function "apply_closure_to_range()" that takes a range of integers (std::ops::Range<i32>) and a closure as arguments. The closure takes an integer and returns another integer. The function applies the closure to each element in the range, transforming them, and returns a new vector containing the transformed elements.

In the "main()" function, an example usage of "apply_closure_to_range()" is demonstrated. It creates a range from 1 to 5 (inclusive), and then applies a closure that multiplies each number by 3. Finally, it prints the modified numbers.

Rust Code Editor:

Previous: Rust String Transformation Function.
Next: Sum with Closure in Rust.

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-7.php