Sub topic 8
Declaring and implementing async fn in traits
This chapter assumes you can write basic async fn code, know that calling one returns a lazy future, and can define traits with generic bounds. Since Rust 1.75, a trait method can be declared async fn, and an impl block can implement it the same way. Before that you needed a crate or a hand-written boxed future.
Declaring an async method
Put async in front of fn in the trait, exactly as you would for a free function. A method can omit the body, or it can have a default body like any other trait method.
trait Storage {
async fn get(&self, key: &str) -> Option<String>;
async fn set(&mut self, key: &str, value: String);
async fn get_or(&self, key: &str, default: &str) -> String {
self.get(key).await.unwrap_or_else(|| default.to_string())
}
}get and set are required methods. get_or is a default method. It calls another async method on self and awaits it, which works because the trait's methods are all part of the same Self type.
All the usual receiver forms are allowed: &self, &mut self, self, and no receiver at all. A method with no receiver, such as async fn open(path: &str) -> Self, is an associated function. It is called as S::open(path).await in generic code.
Implementing the trait
An impl block writes the method as async fn with the same signature. The body can hold .await points like any other async function.
use std::collections::HashMap;
struct MemStore(HashMap<String, String>);
impl Storage for MemStore {
async fn get(&self, key: &str) -> Option<String> {
self.0.get(key).cloned()
}
async fn set(&mut self, key: &str, value: String) {
self.0.insert(key.to_string(), value);
}
}An implementation does not need to contain a real suspension point. MemStore::get never waits, and it is still a valid implementation. A different implementation, such as one backed by a database, can await a network call inside the same method signature.
Implementations can wrap other implementations. This type counts writes and forwards every call to an inner store:
struct CountingStore<S> {
inner: S,
writes: u32,
}
impl<S: Storage> Storage for CountingStore<S> {
async fn get(&self, key: &str) -> Option<String> {
self.inner.get(key).await
}
async fn set(&mut self, key: &str, value: String) {
self.writes += 1;
self.inner.set(key, value).await;
}
}Calling the methods from generic code
Generic code uses the trait through a bound and awaits the result.
async fn greet<S: Storage>(store: &mut S) -> String {
store.set("name", "Ada".to_string()).await;
let name = store.get_or("name", "stranger").await;
let nick = store.get_or("nick", "none").await;
format!("{name}/{nick}")
}A complete program you can run
The standard library has no executor, so this program includes a minimal block_on. It polls in a loop and uses Waker::noop, which is stable since Rust 1.85. It is only suitable for futures that never wait on real I/O, like these. In a real program you would use an executor such as Tokio.
use std::collections::HashMap;
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
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(v) = fut.as_mut().poll(&mut cx) {
return v;
}
}
}
trait Storage {
async fn get(&self, key: &str) -> Option<String>;
async fn set(&mut self, key: &str, value: String);
async fn get_or(&self, key: &str, default: &str) -> String {
self.get(key).await.unwrap_or_else(|| default.to_string())
}
}
struct MemStore(HashMap<String, String>);
impl Storage for MemStore {
async fn get(&self, key: &str) -> Option<String> {
self.0.get(key).cloned()
}
async fn set(&mut self, key: &str, value: String) {
self.0.insert(key.to_string(), value);
}
}
struct CountingStore<S> {
inner: S,
writes: u32,
}
impl<S: Storage> Storage for CountingStore<S> {
async fn get(&self, key: &str) -> Option<String> {
self.inner.get(key).await
}
async fn set(&mut self, key: &str, value: String) {
self.writes += 1;
self.inner.set(key, value).await;
}
}
async fn greet<S: Storage>(store: &mut S) -> String {
store.set("name", "Ada".to_string()).await;
let name = store.get_or("name", "stranger").await;
let nick = store.get_or("nick", "none").await;
format!("{name}/{nick}")
}
fn main() {
let mut store = CountingStore {
inner: MemStore(HashMap::new()),
writes: 0,
};
let out = block_on(greet(&mut store));
println!("{out} writes={}", store.writes);
}It prints Ada/none writes=1. The mutable borrow of store ends when block_on consumes the future, so reading store.writes afterwards is allowed.
What the caller gets back
Each call to an async trait method returns a future, and the future is lazy. Calling store.set(...) without .await runs nothing, and the compiler warns that the future must be used.
The future also borrows from its inputs. For get(&self, key: &str), the returned future may hold both self and key. You cannot drop the String that key points into while the future is alive. The same rule applies to a free async fn with reference parameters. In traits you do not write lifetime annotations for this. The future captures all the lifetimes in scope automatically.
Differences between trait and implementation signatures
The trait and the impl must agree on parameters and output type, but they may differ in how they write the async part. The next chapter covers the desugaring in detail. For now, you need to know that these two forms are interchangeable from the caller's point of view:
use std::future::Future;
trait Clock {
async fn now(&self) -> u64;
}
struct Fixed(u64);
impl Clock for Fixed {
fn now(&self) -> impl Future<Output = u64> {
async { self.0 }
}
}The trait declares async fn, and the impl returns impl Future from a plain fn. The reverse also works. This flexibility matters later, when you want to promise more about the future, such as that it is Send.
| Form | Allowed? | Notes |
|---|---|---|
| `async fn` in trait, `async fn` in impl | Yes | The usual style |
| `async fn` in trait, `fn -> impl Future` in impl | Yes | Useful when you need to control the returned future |
| Default body in the trait | Yes | Can call other methods of the trait with `.await` |
| Generic call `S: Storage` | Yes | Static dispatch, one copy per type |
| `Box<dyn Storage>` or `&dyn Storage` | No | Not dyn compatible, see the callout |
| Recursive call without boxing | No | The future would contain itself, so its size is infinite |
Common mistakes
- Forgetting
.await. The method returns a future, solet v = store.get("k");gives you a future, not anOption<String>. - Expecting
tokio::spawnto accept any generic call. The future fromS::getisSendonly if the compiler can prove it, and for an unknownSit cannot. The error appears at the spawn site, not at the trait. - Holding a borrow across calls. Because the future captures
&mut self, you cannot start a second call on the same value until the first future is finished or dropped. - Reaching for
dyn. Trait objects need a different design from the one in this chapter.
Exercises
Exercise
Add a default method async fn contains(&self, key: &str) -> bool to Storage. Which implementations need to change, and what is the body?
Show answer
None of them. The default body is self.get(key).await.is_some(). MemStore and CountingStore inherit it, because every implementor already provides get.
Exercise
A colleague writes let s: Box<dyn Storage> = Box::new(MemStore(HashMap::new())); and gets a compile error. What is the cause, and what is the simplest fix when only a few concrete store types exist?
Show answer
A trait with async fn methods is not dyn compatible, because each implementor's method returns a future of a different, unnamed type. The simplest fix is to make the calling code generic (fn run<S: Storage>(s: S)) so the compiler uses static dispatch. An enum over the concrete store types also works.