w3resource

Applying Closure to a given number in Rust

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

Write a Rust function that takes a closure as an argument and applies it to a given number.

Sample Solution:

Rust Code:

// Define a function that takes a closure as an argument
fn apply_closure<F: FnOnce(i32) -> i32>(num: i32, closure: F) -> i32 {
    // Call the closure with the given number and return the result
    closure(num)
}

fn main() {
    // Define a closure that squares a number
    let square_closure = |x| x * x;

    // Apply the closure to a given number
    let result = apply_closure(12, square_closure);

    // Print the result
    println!("Result: {}", result); // Output: Result: 144
}

Output:

Result: 144

Explanation:

The above Rust code defines a function called "apply_closure()" that takes two arguments: 'num', an integer, and 'closure', a closure that takes an integer and returns an integer. Inside the function, it calls the closure with the given number 'num' and returns the result.

In the main function,

  • A closure "square_closure" is defined using the |x| x * x syntax, which squares a given number.
  • The "apply_closure()" function is called with arguments 12 and 'square_closure'. This applies "square_closure" to 12.
  • The result of applying closure to 12 is stored in the 'result' variable.
  • The result is printed to the console using "println!()".

Rust Code Editor:


Previous: Rust Closures and Higher-Order Functions Exercises.
Next: Applying Closure to two numbers 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://w3resource.com/rust/functional-programming/rust-closures-and-higher-order-functions-exercise-1.php