Pass a closure to a function by using a generic parameter with a trait bound like Fn, FnMut, or FnOnce.
Pass a closure to a function by defining the parameter with a closure type (like Fn, FnMut, or FnOnce) or using a generic with a trait bound, then call it inside the function body.
fn apply<F>(x: i32, operation: F) -> i32
where
F: Fn(i32) -> i32,
{
operation(x)
}
fn main() {
let double = |x| x * 2;
let result = apply(5, double);
println!("{result}");
}
A closure is a small, anonymous function you can pass around like a variable. You pass it to another function so that function can run your custom logic without you having to write a separate named function. Think of it like handing someone a specific set of instructions to follow when they need to perform a task.