我正在尝试异步调用Future从函数返回的 a 。是否可以?
use core::future::Future;
fn choose_your_adventure<'a>(i: usize) -> Box<&'a dyn Future<Output = ()>> {
match i {
0 => Box::new(&async {}),
_ => Box::new(&async {})
}
}
async fn does_not_work() -> () {
let choice = choose_your_adventure(0);
choice.await; // error[E0277]: `&dyn Future<Output = ()>` is not a future
}
Run Code Online (Sandbox Code Playgroud)
不。轮询未来要求它是可变的。根据设计,不可变引用不能被改变。
在这种情况下,您不需要Box<&dyn ...>. 我会在没有特征对象的情况下编写您的代码:
async fn choose_your_adventure(i: usize) {
match i {
0 => (),
_ => (),
}
}
Run Code Online (Sandbox Code Playgroud)
如果你对一个特质对象感兴趣,那么就没有必要有一个盒装参考:
fn choose_your_adventure(i: usize) -> Box<dyn Future<Output = ()>> {
match i {
0 => Box::new(async {}),
_ => Box::new(async {}),
}
}
Run Code Online (Sandbox Code Playgroud)
尽管使用 futures 箱中的类型别名可能更好:
use futures::{future::BoxFuture, FutureExt}; // 0.3.14
fn choose_your_adventure(i: usize) -> BoxFuture<'static, ()> {
match i {
0 => async {}.boxed(),
_ => async {}.boxed(),
}
}
Run Code Online (Sandbox Code Playgroud)
值得注意的是,它解析为Pin<Box<dyn Future<Output = T> + 'a + Send>>,这表明未来可能会被取消固定(如果T: Unpin)。
也可以看看: