Recursion
Internally, async fn
creates a state machine type containing each
sub-Future
being .await
ed. This makes recursive async fn
s a little
tricky, since the resulting state machine type has to contain itself:
This won't workâwe've created an infinitely-sized type! The compiler will complain:
error[E0733]: recursion in an async fn requires boxing
--> src/lib.rs:1:1
|
1 | async fn recursive() {
| ^^^^^^^^^^^^^^^^^^^^
|
= note: a recursive `async fn` call must introduce indirection such as `Box::pin` to avoid an infinitely sized future
In order to allow this, we have to introduce an indirection using Box
.
Prior to Rust 1.77, due to compiler limitations, just wrapping the calls to
recursive()
in Box::pin
isn't enough. To make this work, we have
to make recursive
into a non-async
function which returns a .boxed()
async
block:
In newer version of Rust, that compiler limitation has been lifted.
Since Rust 1.77, support for recursion in async fn
with allocation
indirection becomes stable, so recursive calls are permitted so long as they
use some form of indirection to avoid an infinite size for the state of the
function.
This means that code like this now works: