rust - 从闭包返回闭包作为函数的返回值

标签 rust closures traits

我正在努力适应 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:

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

就是这样。

因此,您无法形成特征 Fn() -> impl X

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

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

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

How this can be done without using the heap?

您可以从第一个 Fn 返回一个具体实例。

例如,如果您不需要状态,则可以返回一个 fn(bool) -> bool

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

关于rust - 从闭包返回闭包作为函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56201717/

相关文章:

rust - 实现 ParseIntError 的 From 特征

c++ - 如何确定 C++ 中实例化容器模板的容器模板类型

error-handling - 如何处理 rust 上的盒装和链式错误?

rust - 在结构实现中使用不同的生命周期

rust - 为什么 Rust 中没有递增和递减运算符?

error-handling - 如何在不使整个反序列化失败的情况下使用 Serde 解析可能无法反序列化的字段?

laravel - 如何在没有重置值的情况下在 block 函数闭包中创建计数器?

ios - 如何在完成处理程序中传递数据

javascript - 更新 Javascript 闭包中的上下文数组

generics - 类型参数不受 impl 特征、自身类型或谓词的约束