expression
Async state across suspension points
A future generated for an async block retains the live state needed after suspension. The compiler chooses its representation; do not assume a particular memory layout. This example demonstrates a retained local with exactly one self-notified suspension. Expected stdout (not executed): Pending Ready(4) Common mistake: Assuming all locals are recreated from scratch when a suspended future is polled again.
Formal Syntax & Structure
rust syntaxrust
let saved = ...; child.await; use(saved);Working Example
Example Snippetrust
fn main() { use std::{future::Future, task::{Context, Poll, Wake, Waker}, sync::{Arc, atomic::{AtomicBool, Ordering}}}; struct Signal(AtomicBool); impl Wake for Signal { fn wake(self: Arc<Self>) { self.0.store(true, Ordering::SeqCst); } fn wake_by_ref(self: &Arc<Self>) { self.0.store(true, Ordering::SeqCst); } } let signal = Arc::new(Signal(AtomicBool::new(false))); let w = Waker::from(Arc::clone(&signal)); let mut cx = Context::from_waker(&w); let mut f = std::pin::pin!(async { let saved = String::from("note"); let mut first = true; std::future::poll_fn(|cx| { if first { first = false; cx.waker().wake_by_ref(); Poll::Pending } else { Poll::Ready(()) } }).await; saved.len() }); println!("{:?}", f.as_mut().poll(&mut cx)); assert!(signal.0.swap(false, Ordering::SeqCst)); println!("{:?}", f.as_mut().poll(&mut cx));}