Skip to content

Commit a4ee195

Browse files
committed
ref(develop): Update Rust async trait section
1 parent 1353b8a commit a4ee195

File tree

1 file changed

+7
-13
lines changed
  • develop-docs/engineering-practices

1 file changed

+7
-13
lines changed

develop-docs/engineering-practices/rust.mdx

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -50,26 +50,20 @@ During migration you may need normal functions which return futures, for their s
5050

5151
### Async Traits
5252

53-
In **traits** you can not yet use `async fn` ([see this blog post](https://smallcultfollowing.com/babysteps/blog/2019/10/26/async-fn-in-traits-are-hard/)).
54-
In this case, functions should return `-> Pin<Box<dyn Future<Output = ...> + Send>>`:
53+
Support for async in **traits** has [landed in Rust](https://blog.rust-lang.org/2023/12/21/async-fn-rpit-in-traits.html)
54+
and should generally be preferred now.
5555

5656
```rust
57-
trait Database {
58-
fn get_user(&self) -> Pin<Box<dyn Future<Output = User> + Send + '_>>;
59-
}
60-
61-
impl Database for MyDB {
62-
fn get_user(&self) -> Pin<Box<dyn Future<Output = User> + Send + '_>> {
63-
Box::pin(async {
64-
// ...
65-
})
66-
}
57+
pub trait Databse {
58+
fn get_user(&self) -> impl Future<Output = User> + Send;
6759
}
6860
```
6961

7062
Note that the returned future type is `Send`, to ensure that it can run on a multi-threaded runtime.
7163

72-
This corresponds to what the [async-trait crate](https://crates.io/crates/async-trait) does.
64+
When you need dynamic dispatch or have to support Rust versions older than 1.75 consider using the
65+
[`async-trait`](https://docs.rs/async-trait/) crate.
66+
7367

7468
### Avoid `.unwrap()`
7569

0 commit comments

Comments
 (0)