Why does a recursive Rust `async fn count(dir: &Dir) -> u64` that awaits `count(child)` fail with E0733, and how does `Box::pin` fix it?
answer
- a type that contains itself
- awaited futures are stored inline
- indirection gives a known size
- pin, because it is not Unpin
- call-site boxing since 1.77
basics
~20 sEach call's future would have to contain the child call's future, of the same type, inline: an infinitely sized type. Box::pin(count(child)).await moves the child future to the heap so the parent stores only a pointer; since Rust 1.77 that call-site boxing compiles.
solid answer
~40 sAn `async fn`'s future stores the future it is awaiting inline. If `count` awaits `count(child)`, its state machine contains a value of its own type, which has no finite size, so rustc stops with E0733, "recursion in an async fn requires boxing". Writing `Box::pin(count(child)).await` adds indirection: the parent stores a `Pin<Box<...>>` pointer and the child state lives on the heap. Since Rust 1.77 that is accepted; before it, the function had to become a plain `fn` returning `Pin<Box<dyn Future<Output = u64> + '_>>` (or the futures crate's `BoxFuture`) around an `async move` body, a form that still works. `Box::new` alone fails, because `Box<F>` is a `Future` only when `F: Unpin`. Every level costs one heap allocation, so a deep or hot walk may be better as a loop over an explicit stack.
code
rust · 23 linesstruct Dir {
files: u64,
children: Vec<Dir>,
}
async fn count(dir: &Dir) -> u64 {
let mut total = dir.files;
for child in &dir.children {
// Without Box::pin this line is E0733: the future would contain itself.
total += Box::pin(count(child)).await;
}
total
}
fn main() {
let leaf = |files| Dir { files, children: vec![] };
let photos = Dir {
files: 3,
children: vec![leaf(10), Dir { files: 4, children: vec![leaf(7)] }],
};
let total = futures::executor::block_on(count(&photos));
println!("photos holds {total} files");
}go deeper
Recall that a recursive async fn needs Box::pin around the recursive call, and that rustc names the problem as E0733.
Explain why awaited futures are stored inline, so self-recursion makes an infinitely sized type, and why Box::pin rather than Box::new fixes it.
Know both the 1.77 call-site form and the older BoxFuture form, their Send requirements, and when the per-level allocation argues for an explicit worklist.
Judge whether a recursive async algorithm belongs on a hot path at all, or should become an iterative walk with bounded memory and no per-level allocation.
## Why the type would be infinite An `async fn` compiles into a state machine whose value holds, at each `.await`, the **future being awaited, stored inline**. The Async Book illustrates it with an enum: a function that awaits `step_one()` then `step_two()` becomes something like `enum Foo { First(StepOne), Second(StepTwo) }`. Apply that to a recursive directory walk: ```rust async fn count(dir: &Dir) -> u64 { let mut total = dir.files; for child in &dir.children { total += count(child).await; // awaits a future of its own type } total } ``` The future of `count` must contain, while suspended in the loop, a future of type "future of `count`", which contains another, and so on. No finite size exists, so rustc 1.99.1 stops: ```plaintext error[E0733]: recursion in an async fn requires boxing = note: a recursive `async fn` call must introduce indirection such as `Box::pin` to avoid an infinitely sized future ``` E0733 is a **compile-time type-size error**. It has nothing to do with how deep the recursion goes at run time. ## The fix at the call site Box the recursive call: ```rust total += Box::pin(count(child)).await; ``` Now the parent stores a `Pin<Box<impl Future<Output = u64>>>`, which is pointer-sized; the child's state lives on the heap. The error-code index explains the two halves: the `Box` gives the result a known size, and the pin is required to keep it in the same place in memory. ## Why Box::pin and not Box::new `Box::new(count(child)).await` adds the same indirection but still fails. `Box<F>` implements `Future` only when `F: Unpin`, and the future of an `async fn` is not `Unpin` in general. rustc 1.99.1 reports E0283 for this exact code, with the note "cannot satisfy `impl futures::Future<Output = u64>: Unpin`". `Box::pin` returns `Pin<Box<F>>`, which implements `Future` for any `F: Future`. Why the async future is not `Unpin` belongs to the lesson on Pin. ## Before Rust 1.77 Call-site boxing in a recursive `async fn` was stabilised in **Rust 1.77** (release note: "Support async recursive calls (as long as they have indirection)"). Before it, the recursive function could not be `async fn` at all; it had to be an ordinary function that boxes its own body: ```rust fn count(dir: &Dir) -> BoxFuture<'_, u64> { async move { /* same body, calling count(child).await */ }.boxed() } ``` That form still compiles and is common in older code. Note the difference in requirements: | Form | Allocation | Extra bound | |---|---|---| | `Box::pin(count(child)).await` inside `async fn` (1.77+) | one per recursive call | none | | `fn -> BoxFuture<'_, u64>` with `.boxed()` | one per call | the future must be `Send` | | `fn -> LocalBoxFuture<'_, u64>` with `.boxed_local()` | one per call | none | | `fn -> Pin<Box<dyn Future<Output = u64> + '_>>` | one per call | none; dynamic dispatch on poll | `futures::future::BoxFuture` is `Pin<Box<dyn Future<Output = T> + Send + 'a>>`, so `.boxed()` refuses a future that is not `Send`. ## Costs and alternatives - **One heap allocation per level.** A walk over 100,000 directories allocates 100,000 boxes; usually fine for I/O-bound work, noticeable on a hot path. - **Dynamic dispatch** in the boxed-body forms, a small per-poll cost. - **Send-ness** of the boxed future still depends on what the body holds; boxing does not change it. - **No recursion at all**: an explicit worklist (`let mut stack = vec![root];` and `while let Some(dir) = stack.pop()`) needs no boxing and bounds memory by the pending-directory list rather than by call depth. - **Only the recursive edge needs a box.** Non-recursive calls inside the same function stay inline and unboxed. ## Summary for an interview 1. The future of an `async fn` embeds the futures it awaits, so self-recursion would make an infinitely sized type: E0733. 2. `Box::pin` the recursive call to break the cycle with a pointer; it compiles since Rust 1.77. 3. `Box::new` is not enough, because the inner future is not `Unpin`. 4. Older code used a non-async function returning `BoxFuture` or `Pin<Box<dyn Future>>`.
- Does E0733 protect you from a stack overflow on a very deep directory tree?No. E0733 is about the future's type having no finite size at compile time. After boxing, the depth of the walk is bounded only by memory, and each level costs a heap allocation and a nested poll. For untrusted or extremely deep trees, use an explicit worklist loop, or cap the depth yourself.
- Why does the error-code index say the pin is needed, not just the box?The future of an `async fn` may hold references into itself once polled, so it must not move after polling starts; `Box<F>` implements `Future` only for `F: Unpin`. `Pin<Box<F>>` promises the heap value never moves, and it implements `Future` for any `F: Future`, so `.await` accepts it.
- Should you use `.boxed()` or `.boxed_local()` from the futures crate for the old-style recursive function?`.boxed()` returns `BoxFuture`, which is `Pin<Box<dyn Future + Send + 'a>>`, so it only accepts futures that are `Send`, which a multi-threaded spawner needs. If the body holds something non-`Send`, such as an `Rc`, use `.boxed_local()` and `LocalBoxFuture`, or, on 1.77 and later, keep `async fn` with call-site `Box::pin`.
- Recursive async fns are impossible in Rust, so every recursive walk must become a loop.
- Box::new(count(child)).await works just as well as Box::pin.
- E0733 is a runtime guard that stops recursion before the stack overflows.
- Box::pin boxes the whole recursion once, not once per recursive call.
- Current Rust still requires turning the recursive async fn into a plain fn returning a boxed future.
Assumes Rust 1.77 or later (checked on 1.99): Box::pin at the recursive call site compiles since 1.77; older compilers needed a non-async fn returning a boxed future.