Sub topic 8
Declaring and implementing async fn in traits
This chapter covers how to declare async fn methods in a trait, implement them, and call them from generic code. It assumes you know Rust ownership and lifetimes, closures, async/.await basics, and how to write traits with generics and bounds.
Why this matters
Before Rust 1.75, a trait could not contain async fn. You had to box futures by hand or use the async_trait crate. Since Rust 1.75, you can write async fn directly in a trait. This is useful for abstractions such as storage backends, HTTP clients, and database handles, where each implementation does asynchronous work.
Declaring the trait
You write async fn in a trait the same way you write a normal method. The declaration has no body, or it has a default body.
use std::collections::HashMap;
trait Storage {
async fn get(&self, key: &str) -> Option<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 lookup<S: Storage>(store: &S, key: &str) -> String {
store.get(key).await.unwrap_or_default()
}Here is what each part does:
trait Storagedeclaresgetas an async method. Calling it returns a future, as with anyasync fn.impl Storage for MemStorewrites the method withasync fnand a body.MemStoredoes no real waiting, but the signature still has to match the trait.lookupis generic overS: Storage. It callsstore.get(key)and awaits the result.
The future from get borrows &self and key. Because the method is async fn, the compiler ties the returned future to those borrows for you. You don't write any lifetimes.
Calling it from generic code
Generic code treats the method like any other async function. You write the bound S: Storage, call the method, and use .await.
use std::collections::HashMap;
trait Storage {
async fn get(&self, key: &str) -> Option<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 lookup<S: Storage>(store: &S, key: &str) -> String {
store.get(key).await.unwrap_or_default()
}
async fn demo() {
let mut map = HashMap::new();
map.insert("name".to_string(), "Ferris".to_string());
let store = MemStore(map);
assert_eq!(lookup(&store, "name").await, "Ferris");
assert_eq!(lookup(&store, "missing").await, "");
}demo is itself an async fn, so you need an executor such as Tokio to run it. The call is resolved at compile time for MemStore, so no allocation or dynamic dispatch is involved.
Default method bodies
A trait can also give an async method a default body. Implementors may override it.
trait Greeter {
async fn name(&self) -> String;
async fn greet(&self) -> String {
format!("Hello, {}!", self.name().await)
}
}
struct English;
impl Greeter for English {
async fn name(&self) -> String {
"world".to_string()
}
}English only implements name. It gets greet for free, and greet awaits name.
Common errors
- Using the trait as
dyn Storage. This fails because traits withasync fnmethods are not dyn compatible. A later chapter covers boxed futures for this case. - A
Senderror when spawning. Withtokio::spawn, generic code can fail with a message saying the future cannot be sent between threads. A bareasync fnin a trait does not promise aSendfuture. TheSendchapter shows the fix. - A signature mismatch in the impl. If the trait says
&selfand the impl says&mut self, the compiler rejects it, as with any trait method.
Exercise
Write a trait Clock with an async method now(&self) -> u64, then implement it for a struct Fixed(u64) that returns its inner value. What happens if you try to write fn use_it(c: &dyn Clock) {}?
Show answer
The trait is trait Clock { async fn now(&self) -> u64; }, and the impl is impl Clock for Fixed { async fn now(&self) -> u64 { self.0 } }. The &dyn Clock function does not compile, because a trait with an async fn method is not dyn compatible.