Skip to content

Commit f451979

Browse files
committed
async_trait
1 parent cd17c6b commit f451979

File tree

3 files changed

+53
-2
lines changed

3 files changed

+53
-2
lines changed

src/SUMMARY.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,8 +241,9 @@
241241
- [Join](async/control-flow/join_all.md)
242242
- [Select](async/control-flow/select.md)
243243
- [Pitfalls](async/pitfalls.md)
244-
- [Blocking the executor](async/pitfalls/blocking-executor.md)
244+
- [Blocking the Executor](async/pitfalls/blocking-executor.md)
245245
- [Pin](async/pitfalls/pin.md)
246+
- [Async Traits](async/pitfalls/pin.md)
246247
- [Exercises](exercises/day-4/async.md)
247248

248249
# Final Words

src/async/pitfalls.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,6 @@ Async / await provides convenient and efficient abstraction for concurrent async
44

55
---
66

7-
- [Blocking the executor](pitfalls/blocking-executor.md)
7+
- [Blocking the Executor](pitfalls/blocking-executor.md)
88
- [Pin](pitfalls/pin.md)
9+
- [Async Traits](pitfall/async-traits.md)

src/async/pitfalls/async-traits.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Async Traits
2+
3+
Async methods in traits are not yet supported in the stable channel ([An experimental feature exists in nightly and should be stabilized in the mid term.](https://blog.rust-lang.org/inside-rust/2022/11/17/async-fn-in-trait-nightly.html))
4+
5+
The crate [async_trait](https://docs.rs/async-trait/latest/async_trait/) provides a workaround through a macro:
6+
7+
```rust,editable,compile_fail
8+
use async_trait::async_trait;
9+
use tokio::time::{sleep, Duration};
10+
11+
#[async_trait]
12+
trait Sleeper {
13+
async fn sleep(&self);
14+
}
15+
16+
struct FixedSleeper {
17+
sleep_ms: u64,
18+
}
19+
20+
#[async_trait]
21+
impl Sleeper for FixedSleeper {
22+
async fn sleep(&self) {
23+
sleep(Duration::from_millis(self.sleep_ms)).await;
24+
}
25+
}
26+
27+
async fn run_all_sleepers_multiple_times(sleepers: Vec<Box<dyn Sleeper>>, n_times: usize) {
28+
for _ in 0..n_times {
29+
for sleeper in &sleepers {
30+
sleeper.sleep().await;
31+
}
32+
}
33+
}
34+
35+
#[tokio::main]
36+
async fn main() {
37+
let sleepers: Vec<Box<dyn Sleeper>> = vec![
38+
Box::new(FixedSleeper { sleep_ms: 50 }),
39+
Box::new(FixedSleeper { sleep_ms: 100 }),
40+
];
41+
run_all_sleepers_multiple_times(sleepers, 5).await;
42+
}
43+
```
44+
45+
<details>
46+
* Try creating a new sleeper struct that will sleep for a random amount of time and adding it to the Vec.
47+
* Try making the `sleep` call mutable.
48+
* Try adding an associated type for the return value that would return how much time was actually slept.
49+
</details>

0 commit comments

Comments
 (0)