【问题标题】:How can one await a result of a boxed future?一个人怎么能等待一个盒装的未来的结果呢?
【发布时间】:2021-10-29 02:33:06
【问题描述】:
use futures::{future, Future};

fn test() -> Box<dyn Future<Output = bool>> {
    Box::new(future::ok::<bool>(true))
}

async fn async_fn() -> bool {
    let result: bool = test().await;
    return result;
}

fn main(){
    async_fn();
    println!("Hello!");
}

Playground

错误:

error[E0277]: the trait bound `dyn core::future::future::Future<Output = bool>: std::marker::Unpin` is not satisfied
  --> src/main.rs:8:24
   |
8  |     let result: bool = test().await;
   |                        ^^^^^^^^^^^^ the trait `std::marker::Unpin` is not implemented for `dyn core::future::future::Future<Output = bool>`
   |
   = note: required because of the requirements on the impl of `core::future::future::Future` for `std::boxed::Box<dyn core::future::future::Future<Output = bool>>`

【问题讨论】:

标签: rust async-await future


【解决方案1】:

根据the implementation:

impl<F> Future for Box<F>
where
    F: Unpin + Future + ?Sized, 

只有当Box 中的future 实现Unpin 时,盒装future 才实现Future trait。

由于您的函数不保证返回的未来实现Unpin,因此您的返回值将被视为未实现Future。您将无法await 它,因为您的类型基本上不是Future。

@Stargateur 的解决方案,在签名中添加显式类型边界,有效 (Playground):

fn test() -> Box<dyn Future<Output = Result<bool, ()>> + Unpin> 

如果您使用的是futures-rs,则有一个助手类型BoxFuture。您可以使用BoxedFuture,而无需明确声明Unpin:

use futures::future::BoxFuture;

fn test() -> BoxFuture<'static, Result<bool, ()>> {
    Box::pin(async { Ok(true) })
}

Playground

【讨论】:

  • 也非常感谢!帮助我更好地理解,我喜欢期货箱助手的提示。
【解决方案2】:

对于Box 和future,使用Box::pin 代替Box::new 几乎总是有意义的:

use std::pin::Pin;
use futures::{future, Future};

fn test() -> Pin<Box<dyn Future<Output = Result<bool, ()>>>> {
    Box::pin(future::ok(true))
}

async fn async_fn() -> bool {
    test().await.unwrap()
}

原因很有趣。 Pin 有一个blanket implementation for Unpin:

impl<P> Unpin for Pin<P> where
    P: Unpin,

其中的Box&lt;T&gt;是unconditionally Unpin:

impl<T> Unpin for Box<T> where
    T: ?Sized,

所以Pin&lt;Box&lt;dyn Future&gt;&gt; 是未固定的Future。一切正常,但为什么Box 本身没有呢?这是Deref 碍事的地方:

impl<T: ?Sized> Deref for Box<T> {
    type Target = T;
}

await 需要一个未固定的Future,而您使用Box::new 创建的Box&lt;dyn Future&gt; 确实包含Future。因此它会自动取消引用,并且 Unpin 会丢失,除非您使用 Box&lt;dyn Future + Unpin&gt; 明确声明它。


编辑:@ÖmerErden 关于为什么 Box&lt;dyn Future&gt; 不起作用是正确的。

【讨论】:

  • 感谢您对 Unpin + Box 的解释。这帮助很大!
猜你喜欢
  • 2014-02-20
  • 2017-10-03
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 2013-04-26
  • 2019-10-30
  • 2014-05-23
  • 2011-09-04
相关资源
最近更新 更多