如何在新的Future API中清除Future的类型? [英] How do I erase the type of future in the new future API?

查看:93
本文介绍了如何在新的Future API中清除Future的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容无法编译

#![feature(await_macro, async_await, futures_api)]
use core::future::Future;

async fn foo() {}

trait Bar {
    type Output: Future<Output = ()>;
    fn bar(&self) -> Self::Output;
}

impl Bar for () {
    type Output = Box<dyn Future<Output = ()>>;
    fn bar(&self) -> Self::Output {
        Box::new(foo())
    }
}

async fn buz() {
    await!(().bar())
}

error[E0277]: the trait bound `(dyn std::future::Future<Output=()> + 'static): std::marker::Unpin` is not satisfied
  --> src/lib.rs:19:15
   |
19 |     await!(().bar())
   |               ^^^ the trait `std::marker::Unpin` is not implemented for `(dyn std::future::Future<Output=()> + 'static)`
   |
   = note: required because of the requirements on the impl of `std::future::Future` for `std::boxed::Box<(dyn std::future::Future<Output=()> + 'static)>`

error[E0277]: the trait bound `dyn std::future::Future<Output=()>: std::marker::Unpin` is not satisfied
  --> src/lib.rs:19:5
   |
19 |     await!(().bar())
   |     ^^^^^^^^^^^^^^^^ the trait `std::marker::Unpin` is not implemented for `dyn std::future::Future<Output=()>`
   |
   = note: required because of the requirements on the impl of `std::future::Future` for `std::boxed::Box<dyn std::future::Future<Output=()>>`
   = note: required by `std::future::poll_with_tls_waker`
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

如何设置类型Output?我希望bar通过调用foo返回一些Future,以便可以在buz中使用await!.

How can I set the type Output? I want bar to return some Future by calling foo so I can await! in buz.

在过去使用Future<Item = (), Error = ()>的情况下,由于我们没有Unpin约束,但上面也没有任何问题,因此上面的代码可以毫无问题地编译.

In the old days with Future<Item = (), Error = ()>, the above would compile without any problems as we don't have the Unpin constraint, but we also don't have await.

推荐答案

Box包裹在Pin中:

impl Bar for () {
    type Output = Pin<Box<dyn Future<Output = ()>>>;
    fn bar(&self) -> Self::Output {
        Box::pin(foo())
    }
}

这篇关于如何在新的Future API中清除Future的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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