Skip to content

mkulke/async-trait-playground

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

async-trait playground

Context

Rust 1.75 stabilized impl trait in return positions of trait functions. That means it's possible to use specific async trait implementations depending on static feature flags. Before that the async-trait macro had to be used for async trait fn's, which used dynamic dispatch in the background.

A trait like this can be defined and implemented now:

trait Frobnicate {
    async fn frobnicate(&self) -> &str;
}

If we require further trait bounds (e.g we have to add Send b/c we want to call the fn in a multithreaded async runtime) we can desuger the async expression and add the bound:

trait Frobnicate {
    fn frobnicate(&self) -> impl Future<Output = &str> + Send;
}

Sample

cargo r --features=bar -- ohai &
curl http://localhost:3000
ohai
cargo r -- notfoo &
curl http://localhost:3000
foo

About

Using async traits in axum

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages