8 releases (1 stable)

1.0.0 Jan 4, 2022
0.3.2 Feb 2, 2021
0.3.1 Apr 10, 2020
0.2.0 Mar 27, 2020
0.1.2 Oct 4, 2019

#47 in Rust patterns

Download history 94066/week @ 2022-08-14 85811/week @ 2022-08-21 94293/week @ 2022-08-28 89640/week @ 2022-09-04 97436/week @ 2022-09-11 96176/week @ 2022-09-18 98620/week @ 2022-09-25 92878/week @ 2022-10-02 110395/week @ 2022-10-09 107341/week @ 2022-10-16 102932/week @ 2022-10-23 113201/week @ 2022-10-30 110639/week @ 2022-11-06 104841/week @ 2022-11-13 96113/week @ 2022-11-20 99904/week @ 2022-11-27

419,483 downloads per month
Used in 402 crates (184 directly)

MIT/Apache

15KB
191 lines

async-recursion macro

Build Status

Procedural macro for recursive async functions.

Motivation

Consider the following recursive implementation of the fibonacci numbers:

async fn fib(n : u32) -> u64 {
   match n {
       0     => panic!("zero is not a valid argument to fib()!"),
       1 | 2 => 1,
       3     => 2,
       _ => 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) -> u64 {
  |                          ^^^ 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) -> u64 {
   match n {
       0     => panic!("zero is not a valid argument to fib()!"),
       1 | 2 => 1,
       3     => 2,
       _ => 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

~210–610KB
~15K SLoC