Skip to content

Commit

Permalink
ref(develop): Update Rust async trait section (#11950)
Browse files Browse the repository at this point in the history
  • Loading branch information
Dav1dde authored Dec 4, 2024
1 parent c2a1f13 commit 50575e3
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions develop-docs/engineering-practices/rust.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -50,26 +50,26 @@ During migration you may need normal functions which return futures, for their s

### Async Traits

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/)).
In this case, functions should return `-> Pin<Box<dyn Future<Output = ...> + Send>>`:
Support for async in **traits** has [landed in Rust](https://blog.rust-lang.org/2023/12/21/async-fn-rpit-in-traits.html)
and should generally be preferred now.

```rust
trait Database {
fn get_user(&self) -> Pin<Box<dyn Future<Output = User> + Send + '_>>;
pub trait Database {
fn get_user(&self) -> impl Future<Output = User> + Send;
}

impl Database for MyDB {
fn get_user(&self) -> Pin<Box<dyn Future<Output = User> + Send + '_>> {
Box::pin(async {
// ...
})
}
impl Database for MyDatabase {
async fn get_user(&self) -> User {
todo!()
}
}
```

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

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


### Avoid `.unwrap()`

Expand Down

0 comments on commit 50575e3

Please sign in to comment.