blob: 42c01975dd8d3fced33dd3e753a93789c0aa121f (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
An [`async`] function used recursion without boxing.
Erroneous code example:
```edition2018,compile_fail,E0733
async fn foo(n: usize) {
if n > 0 {
foo(n - 1).await;
}
}
```
The recursive invocation can be boxed:
```edition2018
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 body can be boxed:
```edition2018
use std::future::Future;
use std::pin::Pin;
fn foo(n: usize) -> Pin<Box<dyn Future<Output = ()>>> {
Box::pin(async move {
if n > 0 {
foo(n - 1).await;
}
})
}
```
[`async`]: https://doc.rust-lang.org/std/keyword.async.html
|