trait
AsyncFnOnce: consuming async callbacks
A function taking an AsyncFnOnce callback can consume it to obtain one future. The produced future may own data moved from the callback. This is the least restrictive of the three async call-trait bounds for a single call. The fixture-only ready_now helper polls once and rejects Pending; it is not an executor. Expected stdout (not executed): done Common mistake: Requiring AsyncFn for a callback that must move its captured value out.
Formal Syntax & Structure
rust syntaxrust
F: AsyncFnOnce() -> StringWorking 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::ops::AsyncFnOnce; async fn run<F: AsyncFnOnce() -> String>(f: F) -> String { f().await } let message = String::from("done"); let take = async move || message; println!("{}", ready_now(run(take)));}