且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么将闭包传递给接受函数指针的函数不起作用?

更新时间:2023-11-12 09:54:58

闭包不是函数.

您可以将函数传递给需要闭包的函数,但没有理由反过来成立.

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.

例如:

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