How to Pass a Closure as a Function Argument in Rust

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}");
}