异步 fn 中的 Rust 递归

Pin*_*ine 3 recursion asynchronous rust

我想在异步 fn 中使用递归,就像:

async fn test(data: i32) -> i32 {
    if data == 0 {
        0
    } else {
        test(data - 1).await
    }
}
Run Code Online (Sandbox Code Playgroud)

但它说 an 中的递归async fn需要装箱。

所以我把它改成这样:

async fn test(data: i32) -> BoxFuture<'static, i32> {
    async move {
        if data == 0 {
            0
        } else {
            test(data - 1).await.await
        }
    }
    .boxed()
}

Run Code Online (Sandbox Code Playgroud)

但它再次编译错误,并显示消息:计算类型时使用的循环,test::{opaque#0} 我应该做什么来修复它?

caf*_*e25 5

async或多或少是返回 a 的语法糖Future,因为您已经返回了一个,只需从定义中删除 the async,就不再需要它了:

use futures::{FutureExt, future::BoxFuture};
fn test(data: i32) -> BoxFuture<'static, i32> {
    if data == 0 {
        async { 0 }.boxed()
    } else {
        test(data - 1)
    }
}
Run Code Online (Sandbox Code Playgroud)

根据经验,函数应该是或者async返回一个T: Future而不是两者。