std-function
future::poll_fn: implement small poll logic
Wrap a mutable closure as a future. Here the first poll changes an internal flag, requests another poll and returns Pending; the next poll returns its output. This deliberately bounded demonstration does not claim to implement a general timer or I/O operation. Expected stdout (not executed): Pending Ready(21) Common mistake: Returning Pending after changing state without arranging a notification for future progress.
Formal Syntax & Structure
rust syntaxrust
std::future::poll_fn(|cx| -> Poll<T> { ... })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 first = true; let mut f = std::pin::pin!(std::future::poll_fn(|cx| { if first { first = false; cx.waker().wake_by_ref(); Poll::Pending } else { Poll::Ready(21) } })); println!("{:?}", f.as_mut().poll(&mut cx)); assert!(signal.0.swap(false, Ordering::SeqCst)); println!("{:?}", f.as_mut().poll(&mut cx));}