Sub topic 10
Making trait method futures Send
This chapter assumes you know how async fn returns a lazy future, how to write generic functions with trait bounds, and that tokio::spawn needs a Send future. It covers why async fn in a trait does not promise Send, and how to add that promise.
The problem: the trait hides the future type
An async fn in a trait desugars to a method that returns impl Future<Output = T>. The compiler knows the concrete future type for each implementation. Generic code that only sees the trait does not. It sees an anonymous future with no Send guarantee.
This matters with multithreaded executors. tokio::spawn requires the future to be Send, because the runtime may move the task between threads.
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()
}The lookup future holds the future returned by S::get. Since the compiler cannot prove that future is Send, the future from lookup is not Send either. If you pass lookup(&store, "k") to tokio::spawn, you get an error saying the future cannot be sent between threads safely. The error appears at the spawn call, not at the trait.
Fix 1: write the method as `impl Future + Send`
You can declare the method with the Send bound written out. This makes the guarantee part of the trait contract.
use std::future::Future;
trait Fetcher {
fn fetch(&self, id: u64) -> impl Future<Output = String> + Send;
}
struct Local;
impl Fetcher for Local {
async fn fetch(&self, id: u64) -> String {
format!("item {id}")
}
}The implementation can still use async fn. The compiler checks that the resulting future is Send. If an implementor holds a non-Send value, such as an Rc, across an .await, that implementation fails to compile. The error points at the implementation, which is where you want it.
The cost is that every implementor must produce a Send future. A single-threaded implementation can no longer implement the trait.
Fix 2: bound the caller instead
Some traits must stay flexible, for example a library trait used on both single-threaded and multithreaded runtimes. In that case, leave the trait alone and let the caller decide.
Rust has an unstable feature, return type notation, that lets a caller write S: Storage<get(..): Send>. At the time of writing it is not stable, so you cannot rely on it in stable code. On stable Rust, your options are:
- Put
+ Sendin the trait, as above. - Provide two traits, a flexible one and a
Sendone, and implement the second for any type that implements the first withSendfutures. - Use a concrete type in the spawning code, where the compiler can see the real future and prove it is
Send.
The last option works because the compiler checks auto traits on concrete types. Spawning lookup(&MemStore(...), "k") can succeed even though the generic lookup::<S> cannot be proven Send for every S.
Common errors
- Spawning generic code and seeing "future cannot be sent between threads safely". Add a
Sendbound to the trait method, or spawn with a concrete type. - Writing
async fnin the impl butimpl Future + Sendin the trait, then holding anRcor aMutexGuardacross.await. The impl fails to compile. Drop the value before the.await, or use aSendalternative. - Forgetting that
&selfmust also beSyncfor the future to beSend, since the future holds a shared reference.
Exercise
A trait declares async fn get(&self) -> u32;. A generic function run<S: Storage>(s: S) calls s.get().await and you pass run(x) to tokio::spawn. It fails with "future cannot be sent between threads safely". What is the smallest change to the trait that fixes it, and what does it require of implementors?
Show answer
Change the declaration to fn get(&self) -> impl Future<Output = u32> + Send;. Implementors can still write async fn get(&self) -> u32, but the future they return must be Send, so they cannot hold non-Send values such as Rc across an .await.