w3resource

Apply Closure to concatenated strings in Rust

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

Write a Rust function that takes a closure and two strings, concatenates the strings, and applies the closure to the concatenated string.

Sample Solution:

Rust Code:

fn apply_closure_to_strings<F>(str1: &str, str2: &str, closure: F) -> String
where
    F: FnOnce(String) -> String, // Closure trait bound
{
    let concatenated_string = format!("{}{}", str1, str2); // Concatenate the strings
    closure(concatenated_string) // Apply the closure to the concatenated string and return the result
}

fn main() {
    let str1 = "Rust, ";
    let str2 = "Exercises!";
    let result = apply_closure_to_strings(str1, str2, |s| s.to_lowercase()); // Example usage: converting the concatenated string to lowercase
    println!("{}", result); // Print the result
}

Output:

rust, exercises!

Explanation:

In the exercise above,

  • apply_closure_to_strings: This function takes two string slices 'str1' and 'str2', and a closure 'closure' as arguments. The closure takes a "String" and returns a "String".
  • Inside the function, the 'str1' and 'str2' are concatenated using the format! macro to create 'concatenated_string'.
  • The closure 'closure' is then applied to the concatenated string, and the result is returned.
  • In the "main()" function, an example usage of "apply_closure_to_strings()" is demonstrated. It concatenates two strings "Rust, " and "Exercises!", and applies a closure that converts the concatenated string to lowercase.
  • Finally, it prints the result.

Rust Code Editor:


Previous: Sum with Closure in Rust.
Next: Rust Higher-Order function for logical AND.

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