【问题标题】:Is it possible to return a Rust closure that returns a closure without using a Box?是否可以在不使用 Box 的情况下返回一个返回闭包的 Rust 闭包?
【发布时间】:2018-09-29 13:07:35
【问题描述】:

Box中包裹内闭包很容易:

fn add1() -> impl Fn(i32) -> Box<Fn(i32) -> i32> {
    |x| Box::new(|y| x + y)
}

但是有必要使用Box吗?在以下代码中:

fn add2() -> ?? {
    |x: i32| move |y: i32| x + y
}

我可以将?? 替换为进行代码类型检查的东西吗?

【问题讨论】:

    标签: rust closures


    【解决方案1】:

    没有。如您所知,impl Trait 是一种无需装箱即可返回特征实例的机制。

    如果你尝试扩展它:

    fn add2() -> impl Fn(i32) -> impl Fn(i32) -> i32 {
        |x| |y| x + y
    }
    

    编译器告诉你:

    error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
     --> src/lib.rs:9:30
      |
    9 | fn add2() -> impl Fn(i32) -> impl Fn(i32) -> i32 {
      |                              ^^^^^^^^^^^^^^^^^^^
    

    来自impl Trait RFC,强调我的:

    impl Trait 只能写在 a 的返回类型中 独立或固有的实现功能,不在特征定义中或 任何非返回类型的位置。他们也可能不会出现在退货中 闭包特征或函数指针的类型,除非它们是 它们是合法返回类型的一部分。

    • 最终,我们希望允许在特征中使用该功能

    闭包的返回类型是闭包特征的关联类型

    pub trait FnOnce<Args> {
        type Output;
        extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
    }
    

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多