skip to content

Async Functions and Blocks

async fn returns an anonymous future holding every local alive across an .await. Interviewers ask how big that future gets, why recursion needs boxing and what async closures add.

on this pageshow

questions

5

In Rust, what does calling `async fn checksum(data: &[u8]) -> u32` give the caller, and what does that value capture?

level: juniorimportance: must knowfreq 74%

answer

  1. not the number yet
  2. anonymous type, like a closure's
  3. the arrow names the Output
  4. arguments move into the value
  5. the borrow lasts as long as it does

basics

~20 s

A call returns a value of an anonymous compiler-generated type implementing Future with Output = u32, not a u32. That future owns the function's arguments, including the borrowed slice, and runs the body only when it is polled.

solid answer

~40 s

An `async fn` is roughly an ordinary function returning `impl Future<Output = u32>` whose body is an `async move` block. Calling it runs none of the body: it moves every parameter into an anonymous state-machine value and returns that value. Because `data` is a reference, the returned type captures its lifetime, so it is really `impl Future<Output = u32> + 'a` and the slice must outlive the future, or rustc reports E0597. The `-> u32` is the future's `Output`, which you obtain by `.await`ing it in another async context or by handing it to an executor such as `futures::executor::block_on`. Parameters, even unused ones, are dropped when that future completes or is dropped, not when the call returns.

code

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

async fn checksum(data: &[u8]) -> u32 {
    data.iter().map(|b| *b as u32).sum()
}

// Roughly what the compiler turns the async fn into:
fn checksum_desugared<'a>(data: &'a [u8]) -> impl Future<Output = u32> + 'a {
    async move { data.iter().map(|b| *b as u32).sum() }
}

fn main() {
    let image = vec![1u8, 2, 3];
    let fut = checksum(&image); // a future that borrows `image`; nothing summed yet
    let fut2 = checksum_desugared(&image);
    let a = futures::executor::block_on(fut);
    let b = futures::executor::block_on(fut2);
    println!("{a} {b}");
}

go deeper

for a junior

Recall that an async fn call returns a future whose Output is the declared return type, and that you need .await or an executor to get the value.

for a middle

Explain the desugaring to a function returning impl Future with an async move body, and that every parameter and lifetime is captured by the returned future.

for a senior

Diagnose E0597 on a future that outlives borrowed input, and choose between owned parameters and a hand-written impl Future that clones eagerly.

for a principal

Weigh borrowed versus owned parameters in a public async API: borrowing is cheaper per call but ties every future to the caller's data and blocks easy spawning.

## The signature you write and the type you get When you declare `async fn checksum(data: &[u8]) -> u32`, the `-> u32` does **not** describe what a call returns. It describes the **`Output`** of the future that the call returns. The expression `checksum(&image)` evaluates to a value of an **anonymous, compiler-generated type** that implements `std::future::Future<Output = u32>`. You cannot write that type's name: like a closure's type, it exists only inside the compiler, and every `async fn` and every `async` block gets its own distinct one. rustc says so itself when two async blocks meet in an `if`/`else`: "no two async blocks, even if identical, have the same type" (E0308). The Reference describes an `async fn` as **roughly equivalent** to an ordinary function that returns `impl Future` and whose body is an `async move` block: ```rust // Source async fn checksum(data: &[u8]) -> u32 { data.iter().map(|b| *b as u32).sum() } // Roughly what the compiler produces fn checksum<'a>(data: &'a [u8]) -> impl Future<Output = u32> + 'a { async move { data.iter().map(|b| *b as u32).sum() } } ``` Calling it executes none of the body. The value is inert until something polls it; the lesson on futures and polling covers that laziness. What matters here is what the value holds. ## What the returned future captures The Reference states two capture rules for this desugaring: 1. **Every parameter is moved into the future**, including parameters the body never uses and those bound to `_`. They are dropped in the order an ordinary function would drop them, but when the future has been fully awaited (or is dropped early), not when the call returns. 2. **Every lifetime parameter of the declaration is captured** by the return type. `checksum` takes `&'a [u8]`, so its future is `impl Future<Output = u32> + 'a`: it holds the reference and may not outlive the slice. So the future of `checksum` is, conceptually, a small value holding a `&[u8]` plus a marker meaning "not started yet". Once the body contains `.await` points, the same value also stores every local that must survive a suspension, which is why an async fn's future can be far bigger than its arguments. ## Borrowed arguments outlive the call Rule 2 is where people trip. With a synchronous `fn checksum(data: &[u8]) -> u32`, the borrow ends when the call returns. With the async version, the borrow lasts as long as the future exists: ```rust let fut; { let image = vec![1u8, 2, 3]; fut = checksum(&image); // the future keeps borrowing `image` } // `image` is dropped here drop(fut); // error[E0597]: `image` does not live long enough ``` rustc rejects this with **E0597** because the future, still alive on the last line, holds `&image`. The fixes are the ordinary borrow fixes: - keep the data alive until the future has completed; - take an owned parameter (`Vec<u8>`, `Arc<[u8]>`) so the future owns what it reads; - write the function by hand as `fn ... -> impl Future` and copy what you need *before* returning the `async move` block, so the future borrows nothing. ## Getting the u32 out The `u32` exists only once the future has been driven to completion: - inside another `async fn` or `async` block, write `checksum(&image).await`; - from synchronous code, give it to an executor, for example `futures::executor::block_on(checksum(&image))`, since the standard library ships no executor of its own; - or hand it to a runtime's spawn function, which adds `Send` and `'static` requirements covered with spawning. | Form | What the call evaluates to | When the body runs | |---|---|---| | `fn f(x: &[u8]) -> u32` | a `u32` | during the call | | `async fn f(x: &[u8]) -> u32` | an anonymous `impl Future<Output = u32>` that captures `x`'s lifetime | when the future is polled | | `fn f(x: &[u8]) -> impl Future<Output = u32> + '_` returning `async move { .. }` | the same kind of future | statements before the block run during the call; the block runs when polled | ## Why the design matters in practice - **No hidden allocation.** The future is a plain value, on the caller's stack or inside the caller's own future, until someone boxes it. - **No runtime coupling.** An `async fn` returns the same type whichever executor polls it. - **Limited naming.** You cannot write the type in a struct field, so store it generically (`struct Job<F: Future<Output = u32>> { fut: F }`) or erase it into `Pin<Box<dyn Future<Output = u32>>>` at the cost of an allocation. - **Clippy agrees with the sugar.** The `manual_async_fn` lint (warn by default) flags a hand-written `fn ... -> impl Future` whose body is only an `async` block, because the `async fn` form says the same thing more plainly.

  • Can you name the type an `async fn` returns, for example to store it in a struct field?
    Not by name: it is an anonymous opaque type, like a closure's. Keep it generic (`struct Job<F: Future<Output = u32>> { fut: F }`), return it as `impl Future<Output = u32>`, or erase it into `Pin<Box<dyn Future<Output = u32>>>` at the cost of an allocation and dynamic dispatch. Every `async fn` and `async` block has its own type, so two of them never unify without boxing.
  • When are an `async fn`'s parameters dropped, and why can that matter?
    The returned future owns every parameter, even unused ones and `_` patterns, and drops them when it completes or is itself dropped, in the usual parameter order. A large `Vec` argument therefore stays allocated for the future's whole life, and a guard passed by value stays held until the future completes, not until the call returns.
  • When would you write `fn f(x: &[u8]) -> impl Future<Output = u32>` by hand instead of `async fn`?
    When some work must happen eagerly at the call: validating arguments, or cloning what the future needs so it does not borrow `x`. Statements before the returned `async move` block run during the call; the block runs when polled. If the body is only an `async` block, Clippy's `manual_async_fn` lint suggests the `async fn` form instead.

  • Calling an async fn runs its body up to the first .await.
  • The value an async fn call returns is the u32 written after the arrow.
  • A borrowed argument only needs to live until the async fn call returns.
  • Every async fn call heap-allocates its future behind the scenes.
  • Two async fns with identical signatures return the same future type.
open as a page

In Rust, why does `fn greet(name: String) -> impl Future<Output = usize> { async { name.len() } }` fail with E0373, and how does `async move` fix it?

level: middleimportance: must knowfreq 62%

basics

~20 s

A plain async block infers captures like a closure, so it only borrows name, and the returned future would outlive the function that owns it. async move moves name into the future, which then owns it and can be returned.

open as a page

Why does a recursive Rust `async fn count(dir: &Dir) -> u64` that awaits `count(child)` fail with E0733, and how does `Box::pin` fix it?

level: middleimportance: should knowfreq 48%

basics

~20 s

Each call's future would have to contain the child call's future, of the same type, inline: an infinitely sized type. Box::pin(count(child)).await moves the child future to the heap so the parent stores only a pointer; since Rust 1.77 that call-site boxing compiles.

open as a page

In Rust, why does a retry helper bounded by `F: FnMut() -> Fut` reject `|| async { log.push(..) }`, and how does an `AsyncFnMut` bound fix it?

level: seniorimportance: should knowfreq 32%

basics

~20 s

With FnMut() -> Fut, one future type is fixed for every call, so a returned future cannot borrow the closure's captured log. AsyncFnMut, stable since Rust 1.85, lets each call's future borrow the closure's state, so an async closure can push to log.

open as a page

A Rust thumbnail handler keeps a `[u8; 65536]` buffer alive across an `.await`, and `size_of_val` reports a 65 KiB future; why, and how do you shrink it?

level: seniorimportance: should knowfreq 38%

basics

~20 s

An async fn compiles to a state machine that stores every local whose scope spans an .await, so the 64 KiB array sits inside the future. Fix it with a heap buffer, a scope that ends before the .await, or a boxed child future.

open as a page