相关疑难解决方法(0)

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

Rust编程语言第二版(强调我的):

函数指针实现所有三个闭包特征(Fn,FnMutFnOnce),因此您总是可以将函数指针作为期望闭包的函数的参数传递.最好使用泛型类型和闭包特征之一来编写函数,这样您的函数就可以接受函数或闭包.

将闭包传递给接受函数指针作为参数的函数不会编译:

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

11
推荐指数
2
解决办法
1930
查看次数

标签 统计

rust ×1