Rust function for modifying characters with Closure
Rust Closures and Higher-Order Functions: Exercise-12 with Solution
Write a Rust function that takes a closure and a vector of characters. Apply the closure to each character, and returns a new vector of modified characters.
Sample Solution:
Rust Code:
fn apply_closure_to_chars<F>(chars: Vec<char>, closure: F) -> Vec<char>
where
F: Fn(char) -> char, // Closure trait bound
{
chars.into_iter() // Convert the input vector into an iterator
.map(closure) // Apply the closure to each character
.collect() // Collect the modified characters into a new vector
}
fn main() {
let chars = vec!['A', 'B', 'C', 'D', 'E'];
println!("Original characters: {:?}", chars); // Print original characters
let modified_chars = apply_closure_to_chars(chars, |c| c.to_ascii_lowercase()); // Example usage: Convert each character to uppercase
println!("Modified characters: {:?}", modified_chars);
}
Output:
Original characters: ['A', 'B', 'C', 'D', 'E'] Modified characters: ['a', 'b', 'c', 'd', 'e']
Explanation:
In the exercise above,
- apply_closure_to_chars: This function takes a vector of characters 'chars' and a closure 'closure' as arguments. The closure takes a 'char' and returns a 'char'.
- Inside the function, the 'chars' vector is converted into an iterator. The "map()" method is used to apply the closure to each character, transforming each element.
- Finally, the "collect()" method is used to collect the modified characters into a new vector.
- In the "main()" function, an example usage of "apply_closure_to_chars()" function takes a vector of characters and applies a closure that converts each character to uppercase. Finally, it prints the modified characters.
Rust Code Editor:
Previous: Rust function for maximum result with Closure.
Next: Rust Higher-Order function for Tuple modification.
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-12.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics