How do I erase the type of future in the new future API?

扶醉桌前 提交于 2020-01-06 05:15:17

问题


The following does not compile

#![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)

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

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.


回答1:


Wrap the Box in a Pin:

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


来源:https://stackoverflow.com/questions/54452339/how-do-i-erase-the-type-of-future-in-the-new-future-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!