trait-concept
Higher-ranked async callback bounds
A higher-ranked bound accepts borrowed arguments with any caller-chosen lifetime. AsyncFn expresses an input-lifetime-dependent family of futures without forcing all calls to return one named Fut type. The fixture-only ready_now helper polls once and rejects Pending; it is not an executor. Expected stdout (not executed): 5 Common mistake: Requiring every borrowed input to be static or treating Fn(&str) -> Fut as equivalent for lending futures.
Formal Syntax & Structure
rust syntaxrust
F: for<'a> AsyncFn(&'a str) -> usizeWorking 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::AsyncFn; async fn sizes<F: for<'a> AsyncFn(&'a str) -> usize>(f: F) -> usize { let first = String::from("a"); let second = String::from("book"); f(&first).await + f(&second).await } async fn length(s: &str) -> usize { s.len() } println!("{}", ready_now(sizes(length)));}