I'd like to write async functions in a trait, but since async fn
in traits are not supported yet, I am trying to find the equivalent method interface. This is what I have tried in Rust nightly (2019-01-01):
#![feature(await_macro, async_await, futures_api)]
#[macro_use]
extern crate tokio;
use tokio::prelude::*;
trait T {
async fn f();
}
fn main() {
}
error[E0706]: trait fns cannot be declared `async`
--> src/main.rs:7:5
|
7 | async fn f();
| ^^^^^^^^^^^^^
I read somewhere that async
is just impl Future
.
trait T {
fn f() -> impl futures::Future<Item = (), Error = ()>;
}
error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
--> src/lib.rs:2:15
|
2 | fn f() -> impl futures::Future<Item = (), Error = ()>;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Directly returning impl trait
is not allowed, so I tried a boxed trait:
trait Resource {
fn loaded(&self) -> bool;
fn init(&mut self, auth: &str) -> Box<dyn std::future::Future<Output=()>>;
fn prepare(&mut self, auth: &str) -> Box<dyn std::future::Future<Output=()>> {
Box::new(async {
if !self.loaded() {
await!(*(self.init(auth)));
}
})
}
}
[rustc] the size for values of type `dyn std::future::Future<Output=()>` cannot be known at compilation time
Without deref, I get the error that no into_awaitable
exists for Box<>.
Can I use non-Sized impl Future
or *Box<Future>
with await!
? What is the most suitable interface for async functions in the trait?
impl trait
is not allowed" — what makes you say that? – Peter Hall