w3resource

Applying Closure to two numbers in Rust


Write a Rust function that takes a closure and two numbers, and returns the result of applying the closure to the two numbers.

Sample Solution:

Rust Code:

fn apply_closure_to_numbers<F, T>(closure: F, num1: T, num2: T) -> T
where
    F: Fn(T, T) -> T, // Define the closure trait bound
    T: Copy, // Add Copy trait bound for the input types
{
    closure(num1, num2) // Apply the closure to the input numbers
}

fn main() {
    // Define a closure that adds two numbers
    let add_closure = |x, y| x + y;
    
    // Apply the closure to numbers 100 and 200
    let result = apply_closure_to_numbers(add_closure, 100, 200);
    
    // Print the result
    println!("Result: {}", result);
}

Output:

Result: 300

Explanation:

In the exercise above,

  • The "apply_closure_to_numbers()" function takes three generic parameters: 'F', representing the closure type, and 'T', representing the numeric type of the input numbers.
  • The function also specifies trait bounds using the "where" keyword:
    • F: Fn(T, T) -> T indicates that the closure 'F' must accept two arguments of type T and return a value of type 'T'.
    • T: Copy ensures that the input numbers can be copied, allowing them to be passed by value to the closure.
  • Inside the function body, the closure "closure" is applied to the input numbers 'num1' and 'num2', and the result is returned.
  • In the main function, a closure "add_closure" is defined that adds two numbers.
  • The "apply_closure_to_numbers()" function is called with "add_closure" and two numbers (100 and 200), and the result is printed to the console.

Go to:


PREV : Applying Closure to a given number in Rust.
NEXT : Modify vector elements with Rust Closure function.

Rust Code Editor:


What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.