Sum with Closure in Rust
Rust Closures and Higher-Order Functions: Exercise-8 with Solution
Write a Rust function that takes a closure and a slice of integers, applies the closure to each element, and returns the sum of the results.
Sample Solution:
Rust Code:
fn sum_with_closure<F>(slice: &[i32], closure: F) -> i32
where
F: Fn(i32) -> i32, // Closure trait bound
{
// Use the fold method to iterate over the slice, applying the closure to each element and accumulating the sum
slice.iter().map(|&x| closure(x)).sum()
}
fn main() {
let numbers = [1, 2, 3, 4, 5];
println!("Numbers: {:?}", numbers); // Print the numbers
let sum = sum_with_closure(&numbers, |x| x * 2); // Example usage: doubling each element and summing them
println!("Sum: {}", sum); // Print the sum
}
Output:
Numbers: [1, 2, 3, 4, 5] Sum: 30
Explanation:
The above code defines "sum_with_closure()" takes a slice of integers (&[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 slice, transforms them using the closure, and sums up the results. Finally, it returns the sum.
In the "main()" function, an example usage of "sum_with_closure()" is demonstrated. It creates a slice of integers [1, 2, 3, 4, 5] and then applies a closure that doubles each number. Finally, it prints the sum of the transformed numbers.
Rust Code Editor:
Previous: Apply Closure to range in Rust.
Next: Apply Closure to concatenated strings in Rust.
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-8.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics