Sub topic 10
Making trait method futures Send
This chapter assumes you know how async fn returns a lazy future, how Send and Sync work as auto traits, and that you have declared a trait with an async fn method (Rust 1.75 or later). Earlier chapters showed that such a method desugars to a return-position impl Future. This chapter covers the Send problem that desugaring creates in generic code.
Why Send matters for futures
A multithreaded executor such as Tokio's default runtime may move a task between threads while it is suspended at an .await. So tokio::spawn requires the future to be Send. A future is Send only if everything it keeps alive across an .await is Send. That includes captured variables, local variables, and any nested futures.
For a concrete async fn, the compiler sees the whole body and works this out automatically. This is called auto trait leakage: the opaque impl Future type does not name its fields, but the compiler still knows whether they are Send.
The problem in generic code
Auto trait leakage only works when the compiler knows the concrete future type. In generic code it only knows the trait, and the trait says nothing about Send.
use std::future::Future;
trait Storage {
async fn get(&self, key: &str) -> Option<String>;
}
fn require_send<F: Future + Send>(_fut: F) {}
fn check<S: Storage + Sync>(store: &S) {
// error: the future returned by `S::get` is not known to be `Send`
require_send(store.get("k"));
}require_send stands in for tokio::spawn. The call fails because S::get returns an unnamed future type, and the trait makes no promise about it. Adding S: Send + Sync does not help. The bound constrains S, not the future that get returns.
The same trait works fine with a concrete type:
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()
}
}
fn check_concrete(store: &MemStore) {
// Compiles: the compiler sees the concrete future and finds it `Send`.
require_send(store.get("k"));
}The same method is accepted on MemStore and rejected on a generic S. The difference is how much the compiler knows about the future type.
Fix 1: put Send in the trait
You can write the method as a normal function that returns impl Future + Send. This is the same form the compiler desugars async fn into, with an extra bound.
use std::collections::HashMap;
use std::future::Future;
trait Storage {
fn get(&self, key: &str) -> impl Future<Output = Option<String>> + Send;
}
struct MemStore(HashMap<String, String>);
impl Storage for MemStore {
async fn get(&self, key: &str) -> Option<String> {
self.0.get(key).cloned()
}
}
fn require_send<F: Future + Send>(_fut: F) {}
fn check<S: Storage>(store: &S) {
require_send(store.get("k"));
}
fn main() {
let store = MemStore(HashMap::new());
check(&store);
}Three details are worth knowing:
- The implementation can still be written as
async fn. The compiler checks that its future satisfies theSendbound from the trait. - Return-position
impl Traitin a trait captures all lifetimes in scope, including the lifetimes of&selfandkey. You do not need to write+ '_oruse<..>. - Callers now see
Sendthrough the trait, socheckcompiles for everyS: Storage. You did not addS: SendorS: Sync.
What implementors must now satisfy
The guarantee moves the burden to implementors. If an implementation's future holds a non-Send value across an .await, the error appears at the impl, not at the caller.
use std::rc::Rc;
struct Bad;
impl Storage for Bad {
// error: future cannot be sent between threads safely
async fn get(&self, key: &str) -> Option<String> {
let local = Rc::new(key.to_string());
std::future::ready(()).await; // `Rc` is still alive here
Some(local.to_string())
}
}The fix is to drop the Rc before the .await, or to use Arc. Holding &self across an .await also requires Self: Sync, because a shared reference is Send only when its target is Sync. A type with interior mutability that is not Sync, such as one holding a RefCell, cannot implement Storage this way.
The async_fn_in_trait lint
Since Rust 1.75, the compiler warns when a public trait uses plain async fn. The lint is named async_fn_in_trait. It exists for the problem above. Library users cannot add Send bounds to a trait they do not own, so the lint suggests the explicit impl Future + Send form. For a private trait used only inside one crate, with concrete types or a single-threaded runtime, the plain form is fine and you can silence the lint with #[allow(async_fn_in_trait)].
Fix 2: the trait_variant crate
Writing impl Future<Output = ...> + Send for many methods is repetitive. The trait-variant crate, maintained by the Rust project, generates the Send version of a trait from an async fn definition. Add trait-variant = "0.1" to Cargo.toml, then:
#[trait_variant::make(Storage: Send)]
trait LocalStorage {
async fn get(&self, key: &str) -> Option<String>;
}The macro keeps LocalStorage as written, with no Send guarantee, and generates a second trait named Storage whose methods return impl Future + Send. Implement Storage for types that run on multithreaded executors, and use LocalStorage for single-threaded code. This gives you the plain async fn syntax in the source and the Send guarantee in the generated trait.
Fix 3: bound at the call site
Sometimes you want to keep the trait flexible and require Send only in one generic function. The planned feature for this is return type notation, which lets you write a bound on a method's return type:
// Nightly only: requires #![feature(return_type_notation)]
fn check<S>(store: &S)
where
S: Storage,
S::get(..): Send,
{
// ...
}At the time of writing this feature is unstable and not usable on stable Rust. Until it stabilizes, choose between declaring Send in the trait (fix 1 or 2) or accepting that generic code cannot spawn the futures.
Comparing the options
| Approach | Stable | Trait stays usable without Send | Boilerplate |
|---|---|---|---|
| Plain `async fn` in trait | Yes | Yes | None |
| `-> impl Future + Send` in trait | Yes | No | One signature per method |
| `trait_variant::make` | Yes (external crate) | Yes, through the local trait | One attribute |
| Return type notation at the call site | No (nightly) | Yes | One bound per use |
Choosing in practice
- If callers always use concrete types, keep plain
async fn. Auto trait leakage handlesSendfor you. - If generic code spawns the futures on a multithreaded runtime, declare
Sendin the trait or usetrait_variant. - If you need both single-threaded and multithreaded users, use
trait_variantto produce both traits. - If you need
dyn Trait, none of these approaches helps. The next chapters cover boxed futures for that case.
Exercise
A generic function fn run<S: Storage>(s: Arc<S>) calls tokio::spawn(async move { s.get("k").await }), where Storage::get is declared with plain async fn. The compiler rejects it, but the same code with S = MemStore written out compiles. Why, and what is the smallest change to the trait that fixes the generic version?
Show answer
With a concrete type the compiler sees the real future and infers that it is Send. With a generic S it only knows the trait signature, and plain async fn promises nothing about Send. The smallest fix is to change the method to fn get(&self, key: &str) -> impl Future<Output = Option<String>> + Send;. Implementors can still write async fn get.
Exercise
You change Storage::get to return impl Future<Output = Option<String>> + Send. An existing implementor keeps a std::rc::Rc alive across an .await inside its async fn get. Where does the compile error appear, and how do you fix it?
Show answer
The error appears at the impl Storage for ... block, because the implementation's future does not satisfy the trait's Send bound. Fix it by dropping the Rc before the .await (for example by scoping it in a block) or by replacing Rc with Arc.