函数指针实现所有三个闭包特征(
Fn,FnMut和FnOnce),因此您总是可以将函数指针作为期望闭包的函数的参数传递.最好使用泛型类型和闭包特征之一来编写函数,这样您的函数就可以接受函数或闭包.
将闭包传递给接受函数指针作为参数的函数不会编译:
fn main() {
let a = String::from("abc");
let x = || println!("{}", a);
fn wrap(c: fn() -> ()) -> () {
c()
}
wrap(x);
}
Run Code Online (Sandbox Code Playgroud)
error[E0308]: mismatched types
--> src/main.rs:10:10
|
10 | wrap(x);
| ^ expected fn pointer, found closure
|
= note: expected type `fn()`
found type `[closure@src/main.rs:4:13: 4:33 a:_]`
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?
rust ×1