我想在特征中编写异步函数,但是由于尚未支持特征中的async fn
,因此我试图找到等效的方法接口。这是我每晚(2019-01-01)在Rust中都尝试过的事情:
#![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 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
没有解引用,我得到一个错误:into_awaitable
不存在Box<>.
我可以将非大小的impl Future
或*Box<Future>
与await!
一起使用吗?特质中最适合异步功能的接口是什么?
答案 0 :(得分:1)
特征中不允许使用async
函数和impl Trait
。您可以使用关联的类型来接近。这里有一些想法:
pub trait ResourceTrait {
type FutType: Future<Output = ()>;
fn prepare(&mut self, auth: &str) -> Self::Next;
}
实施此操作目前有些棘手,因为某些必需的工具尚不可用,稳定或有故障。
它可以实现为:
impl ResourceTrait for Resource {
type FutType = FutureObj<'static, ()>;
fn prepare(&mut self, auth: &str) -> FutureObj<'static, ()> {
FutureObj::new(Box::new(
async move {
// Do async things
// You might get a lifetime issue here if trying to access auth,
// since it's borrowed.
}
))
}
}
存在类型的替代方法可能是:
impl ResourceTrait for Resource {
// this is required since the real type of the async function
// is unnameable
existential type FutType = Future<Output = ()>;
fn prepare(&mut self, auth: &str) -> Self::FutType {
async move {
// Do async things. Might still encounter the same borrowing issues,
// since the lifetime of the returned Future isn't coupled to the
// lifetime of self.
// The workaround is to make copies of all required fields and move
// them into the Future
}
}
}
这可能会或可能不会(因为该功能正在进行中)。
为了在返回的将来正确借用诸如self
或auth
之类的参数,我们可能还需要首先使用通用关联类型。
为了解决self
的借入问题,您可以定义
struct Resource {
inner: Arc<ResourceInner>, // carries all actual state
}
以便您可以将inner
中的prepare
复制到Future
中。
答案 1 :(得分:1)
如果您可以退还装箱的商品,可以使用async-trait
条板箱:
#![feature(async_await)]
use async_trait::async_trait;
#[async_trait]
trait Advertisement {
async fn run(&self);
}
struct Modal;
#[async_trait]
impl Advertisement for Modal {
async fn run(&self) {
self.render_fullscreen().await;
for _ in 0..4u16 {
remind_user_to_join_mailing_list().await;
}
self.hide_for_now().await;
}
}
struct AutoplayingVideo {
media_url: String,
}
#[async_trait]
impl Advertisement for AutoplayingVideo {
async fn run(&self) {
let stream = connect(&self.media_url).await;
stream.play().await;
// Video probably persuaded user to join our mailing list!
Modal.run().await;
}
}