Pass a closure to a Rust function by defining the parameter with a `Fn` trait bound and calling it inside the function body.
Pass a closure as a function argument by defining the function to accept a parameter with a closure type or a trait bound like Fn, then call that parameter inside the function.
fn apply<F>(x: i32, f: F) -> i32
where
F: Fn(i32) -> i32,
{
f(x)
}
fn main() {
let add_one = |x| x + 1;
let result = apply(5, add_one);
println!("{result}");
}
A closure is a small, anonymous piece of code you can pass around like a variable. You use this when you want to give a function a custom rule to follow without writing a separate named function. Think of it like handing a specific instruction card to a machine so it knows exactly how to process your data.