Sub topic 9
What async fn in a trait desugars to
This chapter assumes you know how async fn returns a lazy future, how to write traits with generics and bounds, and the basics of lifetimes. By the end you should be able to read an async fn in a trait as the signature it stands for, and predict when that signature causes trouble.
The one-line desugaring
Since Rust 1.75, a trait can declare an async fn. The compiler treats the declaration as shorthand for a method that returns impl Future:
use std::future::Future;
trait Storage {
// What you write:
async fn get(&self, key: &str) -> Option<String>;
}
trait StorageDesugared {
// Roughly what it means:
fn get(&self, key: &str) -> impl Future<Output = Option<String>>;
}The second form uses return-position impl Trait in a trait, usually shortened to RPITIT. A plain async fn outside a trait already works the same way: it returns an anonymous type that implements Future. RPITIT extends that idea to trait methods.
Two facts follow from this and explain most of the behavior in the rest of the chapter:
- The return type is opaque. Callers know only that it implements
Future<Output = Option<String>>. - Each implementation chooses its own concrete future type. One impl may return a state machine generated by
async fn, and another may return astd::future::Ready.
Trying both forms
The program below declares both forms of the trait, implements each for the same type, and calls them through generic functions. The block_on helper polls a future with a no-op waker. That works here because every future completes on the first poll. Waker::noop is stable since Rust 1.85.
use std::collections::HashMap;
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
trait Storage {
async fn get(&self, key: &str) -> Option<String>;
}
trait StorageDesugared {
fn get(&self, key: &str) -> impl Future<Output = Option<String>>;
}
struct MemStore(HashMap<String, String>);
impl Storage for MemStore {
async fn get(&self, key: &str) -> Option<String> {
self.0.get(key).cloned()
}
}
impl StorageDesugared for MemStore {
fn get(&self, key: &str) -> impl Future<Output = Option<String>> {
async move { self.0.get(key).cloned() }
}
}
async fn lookup<S: Storage>(store: &S, key: &str) -> String {
store.get(key).await.unwrap_or_default()
}
async fn lookup_desugared<S: StorageDesugared>(store: &S, key: &str) -> String {
store.get(key).await.unwrap_or_default()
}
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
loop {
if let Poll::Ready(value) = fut.as_mut().poll(&mut cx) {
return value;
}
}
}
fn main() {
let mut map = HashMap::new();
map.insert("a".to_string(), "alpha".to_string());
let store = MemStore(map);
let first = block_on(lookup(&store, "a"));
let second = block_on(lookup_desugared(&store, "a"));
assert_eq!(first, second);
println!("{first}");
}The generic functions are identical apart from the bound. Nothing in the caller can tell which form a trait used.
Lifetimes are captured automatically
Look at the signature again: fn get(&self, key: &str) -> impl Future<...>. The returned future uses both self and key, and both have anonymous lifetimes. In a trait, the hidden return type captures every generic parameter and every lifetime in scope. The future may therefore borrow from &self and from key without any annotation.
This is the main reason async fn in traits works without extra lifetime syntax. The older way to get the same effect was a generic associated type (GAT), and you can think of the desugaring as an anonymous version of this:
use std::future::Future;
trait StorageWithGat {
type GetFuture<'a>: Future<Output = Option<String>>
where
Self: 'a;
fn get<'a>(&'a self, key: &'a str) -> Self::GetFuture<'a>;
}This is a mental model, not the literal expansion. The compiler does not give you a nameable associated type, so you cannot write S::GetFuture for S: Storage.
The following diagram shows how one declaration produces a different hidden type per implementor.
Mixing forms between trait and impl
Because both forms mean the same thing, you can pick either one on each side.
| Trait declares | Impl writes | Result |
|---|---|---|
| `async fn` | `async fn` | Normal case. |
| `async fn` | `fn ... -> impl Future<Output = T>` | Allowed. Same contract. |
| `fn ... -> impl Future<Output = T>` | `async fn` | Allowed. Common for libraries, because the trait can add bounds. |
| `fn ... -> impl Future<Output = T> + Send` | `async fn` | Allowed, but the compiler checks that the impl's future is `Send`. |
| `async fn` | `fn ... -> impl Future<Output = T> + Send` | Allowed as a refinement, with a warning by default. |
The last row deserves an example. When an impl promises more than the trait does, callers that use the concrete type can rely on the extra promise. Generic callers still see only the trait's contract. The compiler warns about this because it is easy to do by accident and then break callers when the impl changes. The refining_impl_trait lint covers it, and you silence it when the refinement is intentional:
use std::collections::HashMap;
use std::future::Future;
trait Storage {
async fn get(&self, key: &str) -> Option<String>;
}
struct MemStore(HashMap<String, String>);
impl Storage for MemStore {
#[allow(refining_impl_trait)]
fn get(&self, key: &str) -> impl Future<Output = Option<String>> + Send {
async move { self.0.get(key).cloned() }
}
}
fn assert_send<T: Send>(_: T) {}
fn check(store: &MemStore) {
// Compiles because MemStore's own method promises Send.
assert_send(store.get("a"));
}If check were generic over S: Storage, the same assert_send call would be rejected. The trait itself makes no Send promise.
Consequences of an opaque return type
No promise about Send
An async fn in a trait does not promise that its future is Send. Whether a concrete future is Send depends on what it holds across .await points. A future that keeps an Rc or a MutexGuard from std::sync alive over an await is not Send.
Generic code cannot see that detail. Suppose a function S: Storage hands store.get(..) to a spawn function that requires Send, as tokio::spawn does on a multithreaded runtime. The compiler rejects it, because the trait does not guarantee the bound, even if every impl you have written happens to be Send. The fix is to declare the method as -> impl Future<...> + Send. The next chapter covers that.
Not usable as dyn Trait
Each impl returns a different type, and dyn Trait needs one fixed method signature in its vtable. A trait with async fn is therefore not dyn compatible. A later chapter shows the manual Pin<Box<dyn Future>> workaround and the async_trait crate.
No name for the future
You cannot write the type of the future in a struct field or a type alias. Code that needs to store the pending future must either be generic over it or box it. The ready-made fix for generic code is a helper function that takes the trait and returns its own impl Future, like lookup above.
Return type notation is not stable
A proposed syntax, return type notation, would let a caller write a bound such as S::get(..): Send. It is experimental and requires nightly. On stable Rust, put the Send bound in the trait declaration or use the trait_variant crate to generate a Send variant of a trait.
Common mistakes
- Expecting
Sendfor free. Tests with a single-threaded executor pass. The error shows up when the same generic code is moved totokio::spawn. - Reaching for
dyn.Box<dyn Storage>fails with a dyn compatibility error. This is not a lifetime problem, and adding lifetimes will not fix it. - Silencing
refining_impl_traitwithout thinking. The lint exists because a refined signature becomes part of your public API for callers who use the concrete type. - Believing the trait method allocates. The desugared form does not box anything. The future is a concrete type sized at compile time. Boxing appears only when you ask for it.
- Forgetting that the future borrows its arguments. Because lifetimes are captured,
store.get(&key_string)keepskey_stringborrowed until the future is dropped. Dropping or moving the key before awaiting is a borrow error.
Exercise
Exercise
A trait declares async fn load(&self, id: u32) -> String;. Write the equivalent non-async method signature in the trait. Then say what a generic function fn run<S: Loader>(s: &S) can and cannot assume about the future returned by s.load(1).
Show answer
The signature is fn load(&self, id: u32) -> impl Future<Output = String>;, with use std::future::Future; in scope. The future captures the lifetime of &self, so it may borrow from it. A generic caller can assume only that it implements Future<Output = String>. It cannot assume the future is Send, because the trait does not promise it. It cannot name the future's type, and it cannot assume all impls return the same type. To guarantee Send, declare the method as fn load(&self, id: u32) -> impl Future<Output = String> + Send;.
Exercise
Why does the compiler warn when a trait declares async fn get(&self) -> u8; and an impl writes fn get(&self) -> impl Future<Output = u8> + Send, and what does the warning protect against?
Show answer
The impl promises more than the trait does, because the Send bound is not in the trait. This is a refinement, and the refining_impl_trait lint warns about it. Callers that use the concrete type can start relying on the Send guarantee. If the impl later changes to a future that is not Send, those callers break even though the trait contract is unchanged. Add #[allow(refining_impl_trait)] only when the extra promise is intentional.