Sub topic 9
What async fn in a trait desugars to
This chapter assumes you know how async fn returns a lazy future, how traits and generic bounds work, and basic lifetime elision. It explains what the compiler turns a trait's async fn into, because that explains the Send and dyn limits in the next chapters.
The desugared form
Since Rust 1.75, a trait can declare async fn. The compiler treats it as a method that returns impl Future. This feature is called return-position impl Trait in traits, or RPITIT.
These two declarations mean the same thing:
use std::future::Future;
trait StorageAsync {
async fn get(&self, key: &str) -> Option<String>;
}
trait StorageDesugared {
fn get(&self, key: &str) -> impl Future<Output = Option<String>>;
}Each implementation of the trait gets its own concrete future type. The trait does not name that type. It only promises that the returned type implements Future<Output = Option<String>>. In effect, the trait has a hidden associated type for each async method, and every implementor fills it in.
What the returned future captures
The returned future is allowed to hold references to the arguments. In get(&self, key: &str), the future can borrow from both self and key. An RPITIT return type automatically captures every generic parameter and every lifetime that is in scope, including the elided lifetimes of the reference arguments. You don't write + '_ or a use<..> bound.
This is why a body like self.0.get(key).cloned() works inside an async fn in a trait impl. The future can keep self and key borrowed until it finishes.
Mixing the two forms
The two spellings are interchangeable between a trait and its impls. A trait can declare async fn while an impl writes a plain fn that returns impl Future. The reverse also works. The next example does the first of these:
use std::collections::HashMap;
use std::future::Future;
trait Storage {
async fn get(&self, key: &str) -> Option<String>;
}
struct Cache(HashMap<String, String>);
impl Storage for Cache {
fn get(&self, key: &str) -> impl Future<Output = Option<String>> {
let found = self.0.get(key).cloned();
async move { found }
}
}
async fn show<S: Storage>(store: &S) {
println!("{:?}", store.get("a").await);
}The lookup runs when get is called, not when the future is first polled. The returned future owns found, so it borrows nothing. With an async fn impl, none of the body would run until the first poll. Callers see the same signature either way.
Refining the return type
An impl may promise more than the trait does. If the trait says impl Future<Output = String>, an impl can return impl Future<Output = String> + Send. The compiler accepts this, but it warns with the refining_impl_trait lint. The warning exists because callers who use the concrete type could come to depend on the extra promise. If you mean to do this, silence the lint with #[allow(refining_impl_trait)] on the impl.
The trait itself cannot be refined this way from generic code. When you write S: Storage, you know only what the trait promises, and the trait promises no Send. The next chapter shows how to add it.
| Where you write it | What callers can rely on |
|---|---|
| Trait declares `async fn` | A future with the given output. Nothing about `Send`. |
| Trait declares `-> impl Future<Output = T> + Send` | A `Send` future. |
| Impl returns a refined type, used by its concrete type | The extra promises you wrote, such as `Send`. |
Why this matters for the limits
The hidden return type explains the two main restrictions:
- Generic code cannot tell whether the future is
Send, because the trait says nothing about it. - A trait object has no single concrete future type for the method. This is why
dyn Traitfails, as the dyn chapter shows.
Because of the Send problem, the compiler warns (async_fn_in_trait) when a public trait uses plain async fn.
Exercise
A trait declares async fn load(&self, id: u32) -> String;. Write the equivalent non-async declaration, and say what a generic function bounded by T: Loader can assume about the returned future's Send-ness.
Show answer
fn load(&self, id: u32) -> impl Future<Output = String>; (with use std::future::Future;). A generic function bounded only by T: Loader can assume nothing about Send, because the trait does not promise it. Spawning that future on a multithreaded executor therefore fails to compile unless the trait declares + Send.