15 releases (8 stable)

1.1.1 Apr 25, 2024
1.1.0 Mar 17, 2024
1.0.5 Sep 2, 2023
1.0.4 Mar 18, 2023
0.1.2 Oct 4, 2019

#89 in Rust patterns

Download history 405561/week @ 2024-01-18 413502/week @ 2024-01-25 368129/week @ 2024-02-01 372108/week @ 2024-02-08 342971/week @ 2024-02-15 380917/week @ 2024-02-22 399292/week @ 2024-02-29 396267/week @ 2024-03-07 414430/week @ 2024-03-14 429905/week @ 2024-03-21 417858/week @ 2024-03-28 398165/week @ 2024-04-04 403252/week @ 2024-04-11 418985/week @ 2024-04-18 399150/week @ 2024-04-25 311549/week @ 2024-05-02

1,603,816 downloads per month
Used in 1,343 crates (449 directly)

MIT/Apache

18KB
243 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 returned_future_is_not_send() {
   // ...
}

Sync option

The returned Future doesn't have a Sync bound as it is usually not required. You can include a Sync bound as follows:

#[async_recursion(Sync)]
async fn returned_future_is_sync() {
   // ...
}

In detail:

  • #[async_recursion] modifies your function to return a boxed Future with a Send bound.
  • #[async_recursion(?Send)] modifies your function to return a boxed Future without a Send bound.
  • #[async_recursion(Sync)] modifies your function to return a boxed Future with a Send and Sync bound.

License

Licensed under either of

at your option.

Dependencies

~315–760KB
~18K SLoC