首页 > 解决方案 > 从函数返回未来生成的闭包

问题描述

检查以下代码时:

pub fn producer<F>() -> impl Fn() -> F
where
    F: std::future::Future<Output = ()>,
{
    || async move {
        println!("Hello, World!");
    }
}

我收到以下编译器错误:

error[E0308]: mismatched types
  --> src/lib.rs:5:8
   |
1  |   pub fn producer<F>() -> impl Fn() -> F
   |                   - this type parameter
...
5  |       || async move {
   |  ________^
6  | |         println!("Hello, World!");
7  | |     }
   | |_____^ expected type parameter `F`, found opaque type
   | 
  ::: /Users/tf/.rustup/toolchains/stable-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/future/mod.rs:61:43
   |
61 |   pub const fn from_generator<T>(gen: T) -> impl Future<Output = T::Return>
   |                                             ------------------------------- the found opaque type
   |
   = note: expected type parameter `F`
                 found opaque type `impl Future`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

For more information about this error, try `rustc --explain E0308`.

但是,未来应该最终解决单元。我已经看到了多条错误消息,基本上都与类型不匹配有关,而我怀疑类似丢失Sized标记的东西。但话又说回来,拳击封闭也无济于事。

常见问题:

  1. 是什么让编译器无法接受我的闭包作为正确的类型?
  2. 我该如何解决?

标签: rustasync-awaitfuture

解决方案


推荐阅读