如何才能期待盒装的未来呢? [英] How can one await a result of a boxed future?

查看:97
本文介绍了如何才能期待盒装的未来呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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!");
}

游乐场

错误:

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>>`

推荐答案

根据实现:

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

盒装期货仅在Box内部的期货实现Unpin时实现Future特性.

Boxed futures only implement the Future trait when the future inside the Box implements Unpin.

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

Since your function doesn't guarantee that the returned future implements Unpin, your return value will be considered to not implement Future. You'll not able to await it because your type is basically not a Future.

@Stargateur提供的解决方案可以在签名中添加显式类型边界(

The solution from @Stargateur, adding an explicit type boundary to the signature, works (Playground):

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

如果您使用的是Futures-rs,则有一个助手类型

If you are using futures-rs, there is an helper type BoxFuture. You can use BoxedFuture without explicitly stating Unpin:

use futures::future::BoxFuture;

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

游乐场

这篇关于如何才能期待盒装的未来呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆