gpt4 book ai didi

rust - 为什么递归异步函数需要 Rust 中的“静态参数”?

转载 作者:行者123 更新时间:2023-12-03 11:24:15 24 4
gpt4 key购买 nike

给定一个简单的异步函数:

async fn foo(n: usize) -> usize {
if n > 0 { foo(n - 1).await }
else { 0 }
}

编译器提示 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`.

编译器解释( 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;
}
}
}

最后, future 被包裹在一个固定的盒子里:
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;
}
})
}
Box<...>确保结果的大小已知,
并且需要引脚将其保存在内存中的同一位置。

现在考虑这个代码:
fn foo(n: &usize) -> Pin<Box<dyn Future<Output = usize>>> {
Box::pin(async move {
if *n > 0 {
foo(&n).await
} else {
0
}
})
}

编译器提示 &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


请帮助我了解发生了什么 .

最佳答案

除非另有说明,否则 Trait 对象 ( dyn Trait ) 将默认具有静态生命周期。因此,没有指定生命周期的盒装 future (和其他特征)不能依赖于借用的数据,除非该数据是为 '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
}
})
}

关于rust - 为什么递归异步函数需要 Rust 中的“静态参数”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59538812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com