我希望在一个特质中编写异步函数,但由于尚未支持特质中的
async fn
,因此我正在尝试找到等效的方法接口。这是我在 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();
| ^^^^^^^^^^^^^
我在某个地方读到过,async
只是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 = ()>;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
直接返回impl trait
是不被允许的,所以我尝试了一个包装后的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
没有使用deref,我会得到一个错误,即Box<>
不存在into_awaitable
。
我能否使用非Sized的impl Future
或*Box<Future>
与await!
一起使用?什么是trait中异步函数的最合适接口?
impl trait
是不允许的” — 你为什么这么说? - Peter Hall