为什么将闭包传递给接受函数指针的函数不起作用? [英] Why does passing a closure to function which accepts a function pointer not work?

查看:44
本文介绍了为什么将闭包传递给接受函数指针的函数不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第二版中Rust 编程语言(重点是我的):

In the second edition of The Rust Programming Language (emphasis mine):

函数指针实现了所有三个闭包特征(FnFnMutFnOnce),所以你总是可以通过一个函数指针作为期望闭包的函数的参数.最好使用泛型类型和闭包特征之一编写函数,以便您的函数可以接受函数或闭包.

Function pointers implement all three of the closure traits (Fn, FnMut, and FnOnce), so you can always pass a function pointer as an argument for a function that expects a closure. It’s best to write functions using a generic type and one of the closure traits so your functions can accept either functions or closures.

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

Passing a closure to a function which accepts a function pointer as an argument doesn't compile:

fn main() {
    let a = String::from("abc");

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

    fn wrap(c: fn() -> ()) -> () {
        c()
    }

    wrap(x);
}

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:_]`

为什么这不起作用?

推荐答案

闭包不是函数.

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

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

这篇关于为什么将闭包传递给接受函数指针的函数不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆