从闭包返回闭包作为函数的 return 值

Returning closure from a closure as return value for function

我正在努力适应 impl Fn,但我不明白这段代码的错误:

fn y(state: bool) -> impl Fn() -> impl Fn(bool) -> bool {
    move || {
        println!("state, {}", state);
        |x: bool| {
            println!("state, {}", state);
            !x
        }
    }
}

fn main() {
    y(true)()(true);
}

错误是:

error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
 --> src/main.rs:1:35
  |
1 | fn y(state: bool) -> impl Fn() -> impl Fn(bool) -> bool {
  |                                   ^^^^^^^^^^^^^^^^^^^^^
  1. 为什么第一个 impl Fn 允许,而第二个不允许?
  2. 如何在不使用堆的情况下完成此操作(通过 Box 等)?

如果您仔细阅读邮件,它会准确说明问题所在:

`impl Trait` not allowed outside of function and inherent method return types

目前您只能使用impl Trait:

  • 作为函数的 return 类型:fnimpl 块之外使用。
  • 作为固有方法的 return 类型:fnimpl Type 块中使用。

就是这样。

因此,你无法形成特质Fn() -> impl X

我会注意到,希望这是一个临时限制,因为正在努力扩展可以使用 impl X 的地方,并且需要关联类型和特征方法。

Why is it allowed for the first impl Fn, but not allowed for the second?

第一个 impl Fn 是函数的 return 类型 (y) 所以它是允许的。第二个是 return 类型的特征方法,所以它不是。

How this can be done without using the heap?

您可以 return 第一个 Fn 中的具体实例。

例如,如果您不需要状态,您可以 return 一个 fn(bool) -> bool 代替。

否则,您需要手动创建一个封装所述状态的结构,以便能够命名类型,而不是依赖闭包。