Search code examples
asynchronousrecursionrust

Rust recursion in an async fn


I want to use recursion in an async fn, just like:

async fn test(data: i32) -> i32 {
    if data == 0 {
        0
    } else {
        test(data - 1).await
    }
}

but it says recursion in an async fn requires boxing.

So I change it like this:

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

But it again compile error with message: cycle used when computing type of test::{opaque#0} what should I do to fix it?


Solution

  • async is more or less syntax sugar for returning a Future, since you already return one, just remove the async from your definiton, it's not needed any more:

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

    As a rule of thumb, a function should be either async or return a T: Future not both.