Why does passing a closure to function which accepts a function pointer not work?

A closure isn’t a function.

You can pass a function to a function expecting a closure, but there’s no reason for the reverse to be true.

If you want to be able to pass both closures and functions as argument, just prepare it for closures.

For example:

let a = String::from("abc");

let x = || println!("x {}", a);

fn y() {
    println!("y")
}

fn wrap(c: impl Fn()) {
    c()
}

wrap(x); // pass a closure
wrap(y); // pass a function

Leave a Comment