expression

Async closures can borrow captured state

An async closure can lend captured state to the future produced by a call. The future cannot outlive the required borrow of the closure. A plain closure returning an async block cannot express all such borrowing patterns. The fixture-only ready_now helper polls once and rejects Pending; it is not an executor. Expected stdout (not executed): 4 4 Common mistake: Assuming every future returned by a closure owns all captured data.

Formal Syntax & Structure

rust syntaxrust
let f = async || { ... };

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"),        }    }    let text = String::from("blue");    let length = async || text.len();    println!("{} {}", ready_now(length()), ready_now(length()));}
Rust Reference