w3resource

Rust String Transformation Function

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

Write a Rust function that takes a closure and a vector of strings, applies the closure to each string, and returns a new vector of modified strings.

Sample Solution:

Rust Code:

fn apply_closure_to_strings<F>(strings: Vec<String>, closure: F) -> Vec<String>
where
    F: Fn(String) -> String, // Closure trait bound
{
    strings.into_iter() // Convert the input vector into an iterator
        .map(closure) // Apply the closure to each string and collect the results
        .collect() // Collect the modified strings into a new vector
}

fn main() {
    // Example usage:
    let strings = vec!["rust".to_string(), "exercises".to_string()];
    println!("Original strings: {:?}", strings);
    let modified_strings = apply_closure_to_strings(strings, |s| s.to_uppercase());
    println!("Modified strings: {:?}", modified_strings);  
}

Output:

Original strings: ["rust", "exercises"]
Modified strings: ["RUST", "EXERCISES"]

Explanation:

In the exercise above,

  • The "apply_closure_to_strings()" function takes two parameters:
    • strings: A vector of strings.
    • closure: A closure that takes a string and returns a modified string.
    • Inside the function, "into_iter()" is called on the input vector to convert it into an iterator.
    • The "map()" function is then used to apply the closure to each string in the iterator and collect the results.
    • Finally, the "collect()" function is used to collect the modified strings into a new vector, which is returned.

In the example provided in the "main()" function, the closure |s| s.to_uppercase() converts each string to uppercase. The function "apply_closure_to_strings()" is called with a vector of strings and the closure. The modified strings are printed.

Rust Code Editor:


Previous: Apply Closure Iteratively in Rust.
Next: Apply Closure to range 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-6.php