skip to content

Since Rust 1.75, what does `async fn get(&self, key: &str) -> Option<Vec<u8>>` in a trait desugar to, and what may implementors write?

level: middleimportance: must knowfreq 55%

answer

  1. a hidden return type
  2. one future type per impl
  3. borrows self and every reference argument
  4. async fn or fn returning impl Future

basics

~20 s

It desugars to fn get(&self, key: &str) -> impl Future<Output = Option<Vec<u8>>>: each implementor gets its own hidden future type that borrows self and key. Implementors may write async fn or a plain fn returning impl Future.

solid answer

~40 s

Since Rust 1.75 a trait may declare `async fn`, and rustc treats it as `fn get(&self, key: &str) -> impl Future<Output = Option<Vec<u8>>>` with a hidden, per-implementation return type. That future captures the lifetimes of `&self` and `key`, so both borrows must outlive the `.await`. An implementor may write `async fn` again or the desugared `fn ... -> impl Future<Output = ...>` with an `async move` block, which lets it do synchronous work before building the future. A generic caller (`S: Storage`) gets static dispatch: after monomorphisation it knows each concrete future type, so nothing is boxed. Adding a stronger bound such as `+ Send` in one impl is a refinement rustc warns about with `refining_impl_trait`, and it helps only callers that name that concrete type.

code

rust · 33 lines
rust
use std::future::Future;

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

struct RamStore(Vec<u8>);
impl Storage for RamStore {
    async fn get(&self, _key: &str) -> Option<Vec<u8>> {
        Some(self.0.clone())
    }
}

struct RemoteStore;
impl Storage for RemoteStore {
    // The desugared form: same signature, body as an async block.
    fn get(&self, key: &str) -> impl Future<Output = Option<Vec<u8>>> {
        let url = format!("https://store.example/{key}");
        async move { Some(url.into_bytes()) }
    }
}

// Generic caller: static dispatch, no boxing.
async fn fetch_len<S: Storage>(store: &S, key: &str) -> usize {
    store.get(key).await.map_or(0, |v| v.len())
}

fn main() {
    futures::executor::block_on(async {
        println!("{}", fetch_len(&RamStore(vec![1, 2, 3]), "a").await);
        println!("{}", fetch_len(&RemoteStore, "a").await);
    });
}

go deeper

for a junior

Know that since Rust 1.75 a trait can declare async fn, and that calling it returns a future you must .await to get the value.

for a middle

Explain the desugaring to a hidden impl Future return type, that each impl has its own type, and that the future borrows self and every reference argument.

for a senior

Show when the desugared impl form is worth it, read an E0597 caused by a borrowed key, and know that refining with + Send helps only concrete callers.

for a principal

Treat the hidden type as an API commitment: what you promise about it, such as Send, is fixed once the trait is published.

## What the declaration means Rust 1.75 (December 2023) stabilised `async fn` and return-position `impl Trait` in traits. Before that release a trait could not declare an `async fn` on stable at all, and code reached for the async-trait crate. Today a storage backend trait can be written directly: ```rust trait Storage { async fn get(&self, key: &str) -> Option<Vec<u8>>; } ``` rustc reads this as a method with an **opaque return type**: ```rust fn get(&self, key: &str) -> impl Future<Output = Option<Vec<u8>>>; ``` The `impl Future` here is not one type shared by all implementors. Each `impl Storage for X` supplies its own future type (anonymous when the impl writes `async fn`), and the trait only promises that it implements `Future` with the stated `Output`. Calling `store.get(k)` returns that future; when the impl is an `async fn`, none of its body runs until something polls the future with `.await`. ## What the hidden future captures The returned future **captures every lifetime in scope**: the lifetime of `&self` and the lifetime of `key`. That is what lets the body use `self` and `key` after an `.await`, and it is also a rule callers must respect: - the store must outlive the future; - the `&str` passed as `key` must outlive the future too, even if the implementation never reads it after the first poll; - dropping a `String` you borrowed for `key` before awaiting gives **E0597** ("`key` does not live long enough"). The general capture rules for return-position `impl Trait` belong to the material on `impl Trait`; for trait `async fn` the practical point is that the future is a borrower of all its reference arguments. ## What an implementor may write | Implementor writes | Accepted? | When it helps | |---|---|---| | `async fn get(&self, key: &str) -> Option<Vec<u8>>` | yes | the usual form | | `fn get(&self, key: &str) -> impl Future<Output = Option<Vec<u8>>>` returning `async move { ... }` | yes | do synchronous work first, or move owned data into the future so it borrows less | | the same with `+ Send` added | yes, with a `refining_impl_trait` warning | callers that name this concrete type learn the future is `Send` | | a concrete future type such as `Pin<Box<dyn Future<Output = ...> + '_>>` | yes, with a `refining_impl_trait` warning | rarely; it boxes for no gain to generic callers | The first two forms are interchangeable from the trait's point of view. A refinement (`+ Send`, or a concrete type, in one impl) does **not** change what generic code knows about `S::get`: code written against `S: Storage` still sees only the trait's promise. ## What a generic caller gets 1. **Static dispatch.** `async fn fetch_len<S: Storage>(store: &S, ...)` is monomorphised per backend, so the compiler knows each concrete future type and its size. 2. **No allocation.** The callee's future is stored inline in the caller's own future (or on the stack under `block_on`); nothing is boxed. 3. **No name for the type.** A caller cannot write the future's type in a struct field; if it must store one it uses a generic parameter, or the trait declares an associated type instead of `async fn`. ## What it does not give you - **Trait objects.** A trait with an `async fn` method is not dyn-compatible, so `Box<dyn Storage>` fails with E0038. - **A `Send` guarantee.** Nothing in `async fn get` says the future is `Send`, so a generic caller cannot spawn it onto a multi-threaded executor; rustc's `async_fn_in_trait` lint warns about exactly this on public traits. Both limits, and the async-trait crate and `trait_variant` that work around them, are separate questions; the desugaring above is what they all start from. ## Before and after Rust 1.75 Code written before 1.75 often still carries `#[async_trait]` on traits used only generically. On a current compiler that attribute can usually be removed from such private traits: - the method signatures become the native opaque form, so each call stops allocating a box; - implementors keep writing `async fn` unchanged, once the attribute is removed from the impls too; - what is lost is the automatic `Send` bound on the futures and `dyn` support, so check first that no caller spawns those futures generically or stores the trait as a trait object. For a trait published to other crates the same edit changes public signatures, which makes it a breaking change rather than a clean-up.

  • Does calling a trait `async fn` through a generic `S: Storage` heap-allocate a boxed future?
    No. After monomorphisation the caller knows the concrete future type and its size, so the future is stored inline in the caller's own state machine or on the stack. Boxing appears only when you ask for it: `Box::pin`, a `Pin<Box<dyn Future>>` signature written by hand, or the async-trait crate's expansion.
  • Why might an implementor write the desugared `fn get(...) -> impl Future` form instead of `async fn`?
    To run synchronous code eagerly at call time, such as validating the key or formatting a URL, and then return an `async move` block that owns what it needs. Moving owned data into the block can also keep the future from holding borrows it does not need after the first poll, although the signature still ties it to the argument lifetimes.

  • Async fn in traits still needs the async-trait crate on stable Rust.
  • Every call to a trait async fn allocates a boxed future on the heap.
  • All implementors of the trait share one concrete future type.
  • The returned future copies the key, so the borrow ends when get returns.
  • An impl must repeat async fn; a fn returning impl Future is rejected.

Assumes Rust 1.75 or later (checked on 1.99); async fn in traits was not available on stable before 1.75.