skip to content

Why does a generic Rust fn bounded `S: Storage + Send + Sync + 'static` fail to spawn `async move { store.get(k).await }` when `Storage::get` is a native `async fn`?

level: seniorimportance: should knowfreq 45%

answer

  1. bounds on S, not on its futures
  2. the hidden type's auto traits
  3. concrete callers see more than generic ones
  4. promise Send in the trait

basics

~20 s

Bounds on S say nothing about the hidden future S::get returns, so generic code cannot prove it Send. Declare fn get(...) -> impl Future<Output = T> + Send in the trait, or generate a Send variant with trait_variant.

solid answer

~50 s

A spawn function for a multi-threaded executor requires `F: Future + Send + 'static`, and the `async move` block is `Send` only if everything it holds across `.await` is, including the future returned by `store.get(k)`. `S: Send + Sync` constrains the store, not the anonymous type its `async fn` returns, and native `async fn` in a trait states no auto traits, so rustc reports "future cannot be sent between threads safely". Callers of a concrete type such as `Arc<RamStore>` compile, because rustc can see that type's actual future. The fix puts the promise in the trait: `fn get(&self, key: &str) -> impl Future<Output = Option<Vec<u8>>> + Send`, which implementors still satisfy with `async fn`; `#[trait_variant::make(Storage: Send)]` generates that variant for you. Bounding the method at the call site (`S: Storage<get(..): Send>`, return-type notation) is unstable and fails with E0658.

code

rust · 25 lines
rust
use std::future::Future;
use std::sync::Arc;

trait Storage {
    async fn get(&self, key: &str) -> Option<Vec<u8>>;
}

fn spawn_on_pool<F>(fut: F)
where
    F: Future<Output = ()> + Send + 'static,
{
    futures::executor::block_on(fut);
}

fn warm_cache<S: Storage + Send + Sync + 'static>(store: Arc<S>) {
    spawn_on_pool(async move {
        let _ = store.get("config").await;
    });
}

struct RamStore;
impl Storage for RamStore {
    async fn get(&self, _key: &str) -> Option<Vec<u8>> { Some(vec![1]) }
}
fn main() { warm_cache(Arc::new(RamStore)); }

go deeper

for a junior

Recall that spawning onto a multi-threaded executor needs a Send future and that a generic trait async fn may not give one.

for a middle

Explain that bounds on S constrain the store, not the hidden future type its async fn returns, and why a concrete caller compiles.

for a senior

Fix it at the trait with -> impl Future + Send or trait_variant, read where the error moves afterwards, and know return-type notation is unstable.

for a principal

Weigh promising Send in a public trait: it shuts out single-threaded implementors and cannot be relaxed later without breaking callers.

## The failing code A cache-warming task takes any storage backend and spawns work onto a multi-threaded executor. The spawn function, like a real one, demands `F: Future<Output = ()> + Send + 'static`: ```rust fn warm_cache<S: Storage + Send + Sync + 'static>(store: Arc<S>) { spawn_on_pool(async move { let _ = store.get("config").await; }); } ``` rustc 1.99.1 rejects it (excerpt, source path shortened): ```plaintext error: future cannot be sent between threads safely = help: within `{async block@...}`, the trait `std::marker::Send` is not implemented for `impl futures::Future<Output = Option<Vec<u8>>>` note: future is not `Send` as it awaits another future which is not `Send` ``` The message has no E-code, and it ends with a help suggestion to rewrite `get` as `fn get(...) -> impl Future<...> + Send` in the trait. ## Why the bounds on S are not enough The `async move` block is a state machine. It is `Send` only if every value it keeps across an `.await` is `Send`, and while it awaits `store.get("config")` it holds that call's future. Which type is that? Inside `warm_cache` it is the hidden return type of `<S as Storage>::get`, and the trait says only that it implements `Future<Output = Option<Vec<u8>>>`. - `S: Send + Sync` is a fact about the store, not about the futures its methods build. - An implementor is free to hold an `Rc` or a `std::sync::MutexGuard` across an `.await` inside `get`, so the trait cannot assume the future is `Send`. - Generic code may rely only on what the trait states, so the bound cannot be proved. The same call with a concrete type compiles: in `fn warm(store: Arc<RamStore>)` rustc can see `RamStore`'s own future and that it happens to be `Send`. That is why the error often appears only after code is made generic. Why particular values make a future `!Send` is covered with Send futures and spawning. ## The fixes | Fix | Where the promise lives | Status on 1.99 | |---|---|---| | `fn get(...) -> impl Future<Output = T> + Send` in the trait | every implementor | stable | | `#[trait_variant::make(Storage: Send)]` on a `LocalStorage` trait | a generated `Send` variant, plus the original | stable (crate) | | `#[async_trait]` (async-trait crate) | boxed `dyn Future + Send` | stable (crate), allocates | | `S: Storage<get(..): Send>` at the call site | the caller | unstable, E0658 | 1. **Desugar and bound.** Write the method as `fn get(&self, key: &str) -> impl Future<Output = Option<Vec<u8>>> + Send;`. Implementors still write `async fn get`; an implementor whose future is not `Send` now fails at its own impl ("future returned by `get` is not `Send`"), which is where the mistake is. 2. **Generate both.** `trait_variant::make(Storage: Send)` keeps your `async fn` trait as the local one and emits `trait Storage: Send` whose methods return `impl Future + Send`, with a blanket impl so every `Storage` implementor also implements the local trait. 3. **Box it.** async-trait's default expansion returns `Pin<Box<dyn Future + Send>>`, which also solves dyn use, at an allocation per call. 4. **Return-type notation.** Bounding one method's future at the use site is the eventual language answer, but it is still experimental. ## Diagnosing it in a real codebase The error usually appears far from the trait, after a refactor makes a handler generic over its backend. Reading it in order helps: - the first note points at the awaited call and says the await occurs on a type written `impl Future<...>`, which tells you the culprit is a trait method's hidden future rather than a local such as a guard; - the help line naming the trait method confirms the trait, not the caller, is missing the promise; - if the note instead points at a local value "used across an await", the problem is ordinary future `Send`-ness inside the async block, not the trait. Once the trait is fixed, any implementor that cannot keep the promise surfaces at its own impl, which is the right place for a reviewer to see it. ## The warning that predicted this The `async_fn_in_trait` lint (warn by default) fires on `async fn` in a publicly reachable trait with the message "use of `async fn` in public traits is discouraged as auto trait bounds cannot be specified". It is warning about exactly this failure, and its help notes the trade-off: a `Send` bound added this way "cannot be relaxed without a breaking API change".

  • After the trait says `-> impl Future<Output = T> + Send`, what happens to an implementor that holds an `Rc` across an `.await` in `get`?
    Its impl no longer compiles. rustc 1.99.1 reports "future cannot be sent between threads safely" at the impl, notes "future returned by `get` is not `Send`" and points at the `Rc` held across the `.await`. The error moves from every generic caller to the one implementor that broke the promise.
  • Why does the same `warm` function compile when it takes `Arc<RamStore>` instead of a generic `Arc<S>`?
    With a concrete type rustc knows the actual future type of `RamStore::get` and checks its auto traits directly; that future holds nothing `!Send` across an `.await`, so it is `Send`. Generic code sees only the trait's opaque promise, which says nothing about `Send`.

  • Bounding S: Send + Sync makes every future S's methods return Send.
  • A 'static bound on the store implies its returned futures are Send.
  • Futures returned by trait methods can never be Send without boxing.
  • The fix is to add Send as a supertrait of Storage.
  • Return-type notation like get(..): Send works on stable since 1.75.