Crates.io | async-recursion |
lib.rs | async-recursion |
version | 1.1.1 |
source | src |
created_at | 2019-10-04 00:56:26.118378 |
updated_at | 2024-04-25 16:06:43.164603 |
description | Recursion for async functions |
homepage | |
repository | https://github.com/dcchut/async-recursion |
max_upload_size | |
id | 169753 |
size | 52,401 |
Procedural macro for recursive async functions.
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
.
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
}
}
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() {
// ...
}
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.Licensed under either of
at your option.