|
| 1 | + `async fn`s are not yet supported in traits in Rust. |
| 2 | + |
| 3 | +Erroneous code example: |
| 4 | + |
| 5 | +```compile_fail,edition2018 |
| 6 | +trait T { |
| 7 | + // Neither case is currently supported. |
| 8 | + async fn foo() {} |
| 9 | + async fn bar(&self) {} |
| 10 | +} |
| 11 | +``` |
| 12 | + |
| 13 | +`async fn`s return an `impl Future`, making the following two examples equivalent: |
| 14 | + |
| 15 | +```edition2018,ignore (example-of-desugaring-equivalence) |
| 16 | +async fn foo() -> User { |
| 17 | + unimplemented!() |
| 18 | +} |
| 19 | +// The async fn above gets desugared as follows: |
| 20 | +fn foo(&self) -> impl Future<Output = User> + '_ { |
| 21 | + unimplemented!() |
| 22 | +} |
| 23 | +``` |
| 24 | + |
| 25 | +But when it comes to supporting this in traits, there are [a few implementation |
| 26 | +issues][async-is-hard]. One of them is returning `impl Trait` in traits is not supported, |
| 27 | +as it would require [Generic Associated Types] to be supported: |
| 28 | + |
| 29 | +```edition2018,ignore (example-of-desugaring-equivalence) |
| 30 | +impl MyDatabase { |
| 31 | + async fn get_user(&self) -> User { |
| 32 | + unimplemented!() |
| 33 | + } |
| 34 | +} |
| 35 | +
|
| 36 | +impl MyDatabase { |
| 37 | + fn get_user(&self) -> impl Future<Output = User> + '_ { |
| 38 | + unimplemented!() |
| 39 | + } |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +Until these issues are resolved, you can use the [`async-trait` crate], allowing you to use |
| 44 | +`async fn` in traits by desugaring to "boxed futures" |
| 45 | +(`Pin<Box<dyn Future + Send + 'async>>`). |
| 46 | + |
| 47 | +Note that using these trait methods will result in a heap allocation per-function-call. This is not |
| 48 | +a significant cost for the vast majority of applications, but should be considered when deciding |
| 49 | +whether to use this functionality in the public API of a low-level function that is expected to be |
| 50 | +called millions of times a second. |
| 51 | + |
| 52 | +You might be interested in visiting the [async book] for further information. |
| 53 | + |
| 54 | +[`async-trait` crate]: https://crates.io/crates/async-trait |
| 55 | +[async-is-hard]: https://smallcultfollowing.com/babysteps/blog/2019/10/26/async-fn-in-traits-are-hard/ |
| 56 | +[Generic Associated Types]: https://github.com/rust-lang/rust/issues/44265 |
| 57 | +[async book]: https://rust-lang.github.io/async-book/07_workarounds/06_async_in_traits.html |
0 commit comments