File tree Expand file tree Collapse file tree 3 files changed +53
-2
lines changed Expand file tree Collapse file tree 3 files changed +53
-2
lines changed Original file line number Diff line number Diff line change 241
241
- [ Join] ( async/control-flow/join_all.md )
242
242
- [ Select] ( async/control-flow/select.md )
243
243
- [ Pitfalls] ( async/pitfalls.md )
244
- - [ Blocking the executor ] ( async/pitfalls/blocking-executor.md )
244
+ - [ Blocking the Executor ] ( async/pitfalls/blocking-executor.md )
245
245
- [ Pin] ( async/pitfalls/pin.md )
246
+ - [ Async Traits] ( async/pitfalls/pin.md )
246
247
- [ Exercises] ( exercises/day-4/async.md )
247
248
248
249
# Final Words
Original file line number Diff line number Diff line change @@ -4,5 +4,6 @@ Async / await provides convenient and efficient abstraction for concurrent async
4
4
5
5
---
6
6
7
- - [ Blocking the executor ] ( pitfalls/blocking-executor.md )
7
+ - [ Blocking the Executor ] ( pitfalls/blocking-executor.md )
8
8
- [ Pin] ( pitfalls/pin.md )
9
+ - [ Async Traits] ( pitfall/async-traits.md )
Original file line number Diff line number Diff line change
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 >
You can’t perform that action at this time.
0 commit comments