#traits #async-trait #impl #dynamic-dispatch #async

no-std dynosaur

Dynamic dispatch for return position impl traits and async in Rust

2 releases

0.1.1 Oct 10, 2024
0.1.0 Jul 12, 2024

#233 in Asynchronous

Download history 64/week @ 2024-07-07 18/week @ 2024-07-14 9/week @ 2024-09-15 4/week @ 2024-09-22 172/week @ 2024-10-06 26/week @ 2024-10-13

203 downloads per month

MIT/Apache

12KB
66 lines

Latest Version Documentation GHA Status License

dynosaur lets you use dynamic dispatch on traits with async fn and methods returning impl Trait.

#[dynosaur::dynosaur(DynNext)]
trait Next {
    type Item;
    async fn next(&self) -> Self::Item;
}

The macro above generates a type called DynNext which can be used like this:

async fn dyn_dispatch(iter: &mut DynNext<'_, i32>) {
    while let Some(item) = iter.next().await {
        println!("- {item}");
    }
}

let a = [1, 2, 3];
dyn_dispatch(DynNext::from_mut(&mut a.into_iter())).await;

The general rule is that anywhere you would write dyn Trait (which would result in a compiler error), you instead write DynTrait.

Methods returning impl Trait box their return types when dispatched dynamically, but not when dispatched statically.

License and usage notes

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Dependencies

~240–690KB
~16K SLoC