Skip to content

Commit

Permalink
add an example with async_trait
Browse files Browse the repository at this point in the history
  • Loading branch information
KodrAus committed Jun 1, 2022
1 parent 708a4c5 commit 2188a48
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,5 @@ proc-macro-error = "1.0.0"

[dev-dependencies]
trybuild = "1"
async-trait = "0.1"
async-std = { version = "1", features = ["attributes"] }
32 changes: 32 additions & 0 deletions examples/async_trait.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use std::time::Duration;
use async_std::task;

use async_trait::async_trait;
use auto_impl::auto_impl;

// Note the order of the attributes here:
// `#[async_trait]` must appear first
#[async_trait]
#[auto_impl(&, Box, Arc)]
trait Component {
async fn run(&self);
}

struct WaitABit(Duration);

#[async_trait]
impl Component for WaitABit {
async fn run(&self) {
task::sleep(self.0).await;
}
}

async fn run_async(a: impl Component) {
a.run().await;
}

#[async_std::main]
async fn main() {
// We can treat our `Box<WaitABit>` as an `impl Component` directly
run_async(Box::new(WaitABit(Duration::from_secs(1)))).await;
}

0 comments on commit 2188a48

Please sign in to comment.