trait-concept

Boxed futures for dynamic trait dispatch

Return an erased pinned future through an otherwise dyn-compatible trait. This allows runtime selection of implementations at the cost of boxing and dynamic dispatch. Add Send only when required by the task contract. The fixture-only ready_now helper polls once and rejects Pending; it is not an executor. Expected stdout (not executed): 12 Common mistake: Returning a bare Box<dyn Future> and assuming every underlying future is Unpin.

Formal Syntax & Structure

rust syntaxrust
fn count(&self) -> Pin<Box<dyn Future<Output=u32> + '_>>

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"),        }    }    use std::pin::Pin;    trait Lookup { fn count(&self) -> Pin<Box<dyn Future<Output=u32> + '_>>; }    struct Memory(u32);    impl Lookup for Memory { fn count(&self) -> Pin<Box<dyn Future<Output=u32> + '_>> { Box::pin(async move { self.0 }) } }    let source = Memory(12);    let erased: &dyn Lookup = &source;    println!("{}", ready_now(erased.count()));}
Rust Reference