Last nits

This commit is contained in:
Michael Goulet 2024-01-08 14:31:25 +00:00
parent 841184bcae
commit 9a756034a9
2 changed files with 41 additions and 37 deletions

View file

@ -10,48 +10,30 @@ async fn foo(n: usize) {
}
```
To perform async recursion, the `async fn` needs to be desugared such that the
`Future` is explicit in the return type:
```edition2018,compile_fail,E0733
use std::future::Future;
fn foo_desugared(n: usize) -> impl Future<Output = ()> {
async move {
if n > 0 {
foo_desugared(n - 1).await;
}
}
}
```
Finally, the future is wrapped in a pinned box:
The recursive invocation can be boxed:
```edition2018
use std::future::Future;
use std::pin::Pin;
fn foo_recursive(n: usize) -> Pin<Box<dyn Future<Output = ()>>> {
Box::pin(async move {
if n > 0 {
foo_recursive(n - 1).await;
}
})
async fn foo(n: usize) {
if n > 0 {
Box::pin(foo(n - 1)).await;
}
}
```
The `Box<...>` ensures that the result is of known size, and the pin is
required to keep it in the same place in memory.
Alternatively, the recursive call-site can be boxed:
Alternatively, the body can be boxed:
```edition2018
use std::future::Future;
use std::pin::Pin;
fn foo_recursive(n: usize) -> impl Future<Output = ()> {
async move {
fn foo(n: usize) -> Pin<Box<dyn Future<Output = ()>>> {
Box::pin(async move {
if n > 0 {
Box::pin(foo_recursive(n - 1)).await;
foo(n - 1).await;
}
}
})
}
```