Skip to content

Commit

Permalink
update original
Browse files Browse the repository at this point in the history
  • Loading branch information
funkill committed Oct 11, 2024
1 parent 8a42327 commit 2a46fbe
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
7 changes: 7 additions & 0 deletions async-book/examples/07_05_recursion/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,10 @@ fn recursive() -> BoxFuture<'static, ()> {
}.boxed()
}
// ANCHOR_END: example

// ANCHOR: example_pinned
async fn recursive_pinned() {
Box::pin(recursive_pinned()).await;
Box::pin(recursive_pinned()).await;
}
// ANCHOR_END: example_pinned
27 changes: 22 additions & 5 deletions async-book/src/07_workarounds/04_recursion.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,38 @@ 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:22
error[E0733]: recursion in an async fn requires boxing
--> src/lib.rs:1:1
|
1 | async fn recursive() {
| ^ an `async fn` cannot invoke itself directly
| ^^^^^^^^^^^^^^^^^^^^
|
= note: a recursive `async fn` must be rewritten to return a boxed future.
= 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`.
Unfortunately, compiler limitations mean that just wrapping the calls to

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:

```rust,edition2018
{{#include ../../examples/07_05_recursion/src/lib.rs:example}}
```

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:

```rust,edition2021
{{#include ../../examples/07_05_recursion/src/lib.rs:example_pinned}}
```

[becomes stable]: https://blog.rust-lang.org/2024/03/21/Rust-1.77.0.html#support-for-recursion-in-async-fn
[that compiler limitation has been lifted]: https://github.com/rust-lang/rust/pull/117703/

0 comments on commit 2a46fbe

Please sign in to comment.