#async #recursion

macro async-recursion

Recursion for async functions

13 releases (6 stable)

1.0.5 Sep 2, 2023
1.0.4 Mar 18, 2023
1.0.2 Jan 19, 2023
1.0.0 Jan 4, 2022
0.1.2 Oct 4, 2019

#94 in Rust patterns

Download history 348777/week @ 2023-10-31 335394/week @ 2023-11-07 362707/week @ 2023-11-14 309553/week @ 2023-11-21 341398/week @ 2023-11-28 343800/week @ 2023-12-05 322392/week @ 2023-12-12 274349/week @ 2023-12-19 185574/week @ 2023-12-26 306316/week @ 2024-01-02 320741/week @ 2024-01-09 378926/week @ 2024-01-16 415729/week @ 2024-01-23 401737/week @ 2024-01-30 359442/week @ 2024-02-06 302424/week @ 2024-02-13

1,547,791 downloads per month
Used in 1,190 crates (414 directly)

MIT/Apache

16KB
205 lines

async-recursion macro

Latest version crates.io downloads Build Status Apache/MIT2.0 License

Procedural macro for recursive async functions.

Motivation

Consider the following recursive implementation of the fibonacci numbers:

async fn fib(n : u32) -> u32 {
   match n {
       0 | 1 => 1,
       _ => fib(n-1).await + fib(n-2).await
   }
}

The compiler helpfully tells us that:

error[E0733]: recursion in an `async fn` requires boxing
 --> src/main.rs:1:26
  |
1 | async fn fib(n : u32) -> u32 {
  |                          ^^^ recursive `async fn`
  |
  = note: a recursive `async fn` must be rewritten to return a boxed `dyn Future`
  = note: consider using the `async_recursion` crate: https://crates.io/crates/async_recursion

This crate provides an attribute macro to automatically convert an async function to one returning a boxed Future.

Example

use async_recursion::async_recursion;

#[async_recursion]
async fn fib(n : u32) -> u32 {
   match n {
      0 | 1 => 1,
      _ => fib(n-1).await + fib(n-2).await
   }
}

?Send Option

The returned future has a Send bound to make sure it can be sent between threads. If this is undesirable you can mark that the bound should be left out like so:

#[async_recursion(?Send)]
async fn example() {
   // ...
}

In detail:

  • #[async_recursion] modifies your function to return a BoxFuture, and
  • #[async_recursion(?Send)] modifies your function to return a LocalBoxFuture.

License

Licensed under either of

at your option.

Dependencies

~330–780KB
~19K SLoC