expression
Async recursion with an erased return type
An ordinary function can return a boxed async block. Each invocation returns a pointer-sized handle to its future storage instead of a recursively nested concrete future. This also erases the underlying type. The fixture-only ready_now helper polls once and rejects Pending; it is not an executor. Expected stdout (not executed): 3 Common mistake: Assuming erased futures automatically implement Send or do not allocate.
Formal Syntax & Structure
rust syntaxrust
fn visit(n: u32) -> Pin<Box<dyn Future<Output=u32>>>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"), } } use std::pin::Pin; fn steps(n: u32) -> Pin<Box<dyn Future<Output=u32>>> { Box::pin(async move { if n == 0 { 0 } else { 1 + steps(n-1).await } }) } println!("{}", ready_now(steps(3)));}