给定一个简单的异步函数:
async fn foo(n: usize) -> usize {
if n > 0 { foo(n - 1).await }
else { 0 }
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨async fn必须重写以返回一个装箱的dyn Future.
| async fn foo(n: usize) -> usize {
| ^^^^^ recursive `async fn`
= note: a recursive `async fn` must be rewritten to return a boxed `dyn Future`.
For more information about this error, try `rustc --explain E0733`.
Run Code Online (Sandbox Code Playgroud)
编译器说明 ( rustc --explain E0733):
为了实现异步递归,async fn需要去糖化,使得Future返回类型中的是显式的:
use std::future::Future;
fn foo_desugared(n: usize) -> impl Future<Output = ()> {
async move {
if n > 0 {
foo_desugared(n - 1).await;
}
}
}
Run Code Online (Sandbox Code Playgroud)
最后,未来被包裹在一个固定的盒子里:
use std::future::Future;
use std::pin::Pin;
fn foo_recursive(n: usize) -> Pin<Box<dyn Future<Output = ()>>> {
Box::pin(async move {
if n > 0 {
foo_recursive(n - 1).await;
}
})
}
Run Code Online (Sandbox Code Playgroud)
该Box<...>确保的结果是已知大小的,并且销必须保持它在存储器中的相同位置。
现在考虑这个代码:
fn foo(n: &usize) -> Pin<Box<dyn Future<Output = usize>>> {
Box::pin(async move {
if *n > 0 {
foo(&n).await
} else {
0
}
})
}
Run Code Online (Sandbox Code Playgroud)
编译器抱怨 的生命周期&n应该是'static。
| fn foo(n: &usize) -> Pin<Box<dyn Future<Output = usize>>> {
| ------ help: add explicit lifetime `'static` to the type of `n`: `&'static usize`
| / Box::pin(async move {
| | if *n > 0 {
| | foo(&n).await
| | } else {
| | 0
| | }
| | })
| |______^ lifetime `'static` required
Run Code Online (Sandbox Code Playgroud)
请帮助我了解发生了什么。
dyn Trait默认情况下,特质对象 ( ) 将具有静态生命周期,除非另有说明。因此,没有指定生命周期的盒装期货(和其他特征)不能依赖于借用数据,除非该数据在'static生命周期内被借用。(这是您的错误消息所抱怨的)。
要解决这个问题,您可以明确指定生命周期,也可以只使用'_,在这种情况下,它将使用n: &usize参数的省略生命周期:
// .-- will use elided lifetime from here
// v v-- give the future a non-'static lifetime
fn foo(n: &usize) -> Pin<Box<dyn '_ + Future<Output = usize>>> {
// or: fn foo<'a>(n: &'a usize) -> Pin<Box<dyn 'a + Future<Output = usize>>>
Box::pin(async move {
if *n > 0 {
foo(&n).await // <-- no error, as the future lifetime now depends on the
// lifetime of n instead of having a 'static lifetime
} else {
0
}
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
771 次 |
| 最近记录: |