expression

Async recursion: box the recursive call

A direct recursive async future cannot contain an unbounded chain of itself by value. Introduce indirection at the recursive edge; bounded input still matters for allocations, polling and destruction depth. The fixture-only ready_now helper polls once and rejects Pending; it is not an executor. Expected stdout (not executed): 10 Common mistake: Assuming boxing makes arbitrary recursion safe from resource exhaustion.

Formal Syntax & Structure

rust syntaxrust
Box::pin(recurse(n - 1)).await

Working Example

Example Snippetrust
fn main() {    use std::{future::Future, task::{Context, Poll, Waker}};    fn ready_now<F: Future>(f: F) -> F::Output {        let mut f = std::pin::pin!(f);        let mut cx = Context::from_waker(Waker::noop());        match f.as_mut().poll(&mut cx) {            Poll::Ready(value) => value,            Poll::Pending => panic!("fixture expected immediate readiness"),        }    }    async fn sum(n: u32) -> u32 {        if n == 0 { 0 } else { n + Box::pin(sum(n-1)).await }    }    println!("{}", ready_now(sum(4)));}
Rust Reference