skip to content

Asynchronous Programming

Async Rust compiles async fn into state machines driven by a runtime the language does not ship. Interviewers test polling, Pin, Send futures, async traits and cancellation.

on this pageshow

explore

questions

page 1 of 2

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, a sensor gateway calls an async fn that sends a reading but forgets the .await; what happens, and why?

level: juniorimportance: must knowfreq 80%

basics

~20 s

Nothing is sent. Calling an async fn only builds a future; its body runs when that future is polled, normally through .await. The unawaited future is dropped at the end of the statement, and rustc warns through unused_must_use.

open as a page

Rust's standard library defines `Future` and `async`/`.await` but no runtime, so how does a Rust program actually run an async function from `main`?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Rust's std ships the Future trait and async syntax but no executor, and rustc rejects async fn main (E0752). A synchronous main passes the top-level future to an executor's block_on, such as futures::executor::block_on or smol::block_on.

open as a page

In Rust, why does a multi-threaded executor's spawn function demand a future that is both `Send` and `'static`, and how does `async move` help?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A spawned future may be resumed on any worker thread and may outlive the function that spawned it, so the spawn function requires Send and 'static. An async move block owns the variables it captures instead of borrowing them.

open as a page

In Rust, what changes when you pass two futures to `futures::join!` instead of awaiting them one after the other?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Sequential awaits run the futures one after the other, so the waits add up. futures::join! polls both on one task, interleaving them at each .await, so the total is about the longest wait: concurrency, not parallelism.

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

In Rust 1.75 and later, when is the async-trait crate's `#[async_trait]` still needed, and what does it cost per call?

level: middleimportance: must knowfreq 60%

basics

~20 s

Since 1.75, async-trait is needed mainly for dyn Trait use of async methods, or code supporting older compilers. Each call returns Pin<Box<dyn Future + Send>>: one heap allocation and dynamic poll dispatch, with Send required unless ?Send is used.

open as a page

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%

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.

open as a page

In Rust, when a payment worker's async fn future is dropped while suspended at `db_write(id).await`, which of its statements still run?

level: middleimportance: must knowfreq 62%

basics

~20 s

Dropping the future cancels it: no statement after the pending .await ever runs, so the acknowledgement is skipped. Statements before it already ran, and each local still alive at that .await has its Drop run as the future is dropped.

open as a page

In Rust, what does .await actually do with a future, and how does a Poll::Pending from deep inside reach the executor?

level: middleimportance: must knowfreq 55%

basics

~20 s

.await calls IntoFuture::into_future, then polls the future with the current task's Context. If it returns Poll::Pending, the enclosing async body returns Pending too, the chain unwinds to the executor, and the task is polled again after its Waker fires.

open as a page

In a Rust async handler, why does a blocking compression call or `std::thread::sleep` stall other tasks, and how do you offload it?

level: middleimportance: must knowfreq 66%

basics

~20 s

A Rust task yields its thread only when an .await returns Pending, so a blocking call holds the executor thread and other tasks on it wait. Move the call to a thread pool, for example smol::unblock, and await the result.

open as a page

A Rust chat server's handler locks a `std::sync::Mutex`, then awaits a broadcast; why does spawning it fail, and how do you fix it?

level: middleimportance: must knowfreq 80%

basics

~20 s

The handler's future stores every local that is alive at an .await, and std's MutexGuard is deliberately not Send, so the future is not Send and a multi-threaded spawn rejects it. Release the guard in an inner block before awaiting.

open as a page

A Rust `Storage` trait with a native `async fn get` fails with E0038 at `Vec<Box<dyn Storage>>`: why, and what are the stable fixes?

level: seniorimportance: must knowfreq 50%

basics

~20 s

An async fn method returns a hidden future type that differs per implementor, and a vtable slot cannot describe it. Fixes: return Pin<Box<dyn Future>> (by hand or with async-trait), add a boxed companion trait, or use an enum.

open as a page

In Rust, what makes an async read method cancellation-safe, and why does a frame reader collecting bytes into a local `Vec` lose data when dropped?

level: seniorimportance: must knowfreq 50%

basics

~20 s

An async method is cancellation-safe when dropping its future before completion loses nothing, so a later call resumes cleanly. A frame reader that moves bytes into a local Vec loses them on drop, because that Vec lives only in the future.

open as a page

In Rust, why can an `async fn` future that borrows its own local buffer across an `.await` not be moved once polled, and how does `Pin` stop that?

level: seniorimportance: must knowfreq 55%

basics

~20 s

Locals alive across an .await live inside the future, so a borrow of a local array points into the future itself. Future::poll takes Pin<&mut Self>, and safe code gets no &mut to a pinned !Unpin future to move it.

open as a page

In Rust, what is the difference between pinning a future with `std::pin::pin!` and with `Box::pin`, and when do you use each?

level: juniorimportance: should knowfreq 40%

basics

~20 s

pin! (stable since Rust 1.68) pins a future in the current scope's local storage and returns Pin<&mut F>, with no allocation but no escape. Box::pin moves it to the heap and returns an owned Pin<Box<F>> you can return or store.

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, when a timeout fires before a payment write's future completes, what happens to that future, and can the write still have landed?

level: middleimportance: should knowfreq 48%

basics

~20 s

A timeout wrapper drops the write's future at its pending .await, so the worker never runs the code after it. Dropping is not rollback: if the request already reached the database, the write may still commit, so the outcome is unknown, not failed.

open as a page

In Rust, why do `futures::future::select(fut, tick)` and `(&mut fut).await` on an `async fn` future fail with E0277 "cannot be unpinned", and what fixes it?

level: middleimportance: should knowfreq 45%

basics

~10 s

futures::future::select and impl Future for &mut F require F: Unpin, and rustc never makes an async future Unpin. Pin it first with std::pin::pin! (or Box::pin to keep it) and pass fut.as_mut().

open as a page

In Rust, what does the `Unpin` auto trait mean, which types implement it, and what does `Pin<&mut T>` restrict when `T: Unpin`?

level: middleimportance: should knowfreq 45%

basics

~20 s

Unpin marks a type that does not rely on staying at one address once pinned. Almost every type gets it automatically; async futures and types holding PhantomPinned do not. For T: Unpin, Pin<&mut T> restricts nothing beyond &mut T.

open as a page

In a Rust async runtime, what is the difference between the executor and the reactor, and which does `futures::executor::block_on` provide?

level: middleimportance: should knowfreq 45%

basics

~20 s

The executor polls woken tasks; the reactor waits on the operating system for I/O and timers and calls the stored Waker. futures::executor::block_on is only an executor: it polls, then parks the thread until the waker unparks it.

open as a page

When rustc decides whether an `async fn`'s future is `Send`, which values does it count as held across an `.await`?

level: middleimportance: should knowfreq 55%

basics

~20 s

The future holds every argument of the async fn, every local whose scope spans an .await even if never used again, temporaries alive at the await, and the future being awaited. One non-Send value among them makes it non-Send.

open as a page

How would a Rust crawler fetch 500 URLs with at most 16 in flight, handling each result as it arrives, using futures streams?

level: middleimportance: should knowfreq 55%

basics

~10 s

Build stream::iter(urls).map(fetch).buffer_unordered(16) and loop with while let Some(r) = results.next().await. map creates each request future lazily, and buffer_unordered keeps at most 16 polled at once, yielding each result as it finishes.

open as a page

What is Rust's futures `Stream` trait, and why is it consumed with `while let Some(x) = s.next().await` instead of `for`?

level: middleimportance: should knowfreq 45%

basics

~10 s

Stream is the async counterpart of Iterator: poll_next returns Poll<Option<Item>>. A stable for loop only takes IntoIterator, so you await StreamExt::next, which yields Option<Item>, in a while let loop until it returns None.

open as a page

With Rust's `futures::try_join!`, what happens to the other futures when one of them resolves to `Err`?

level: middleimportance: should knowfreq 48%

basics

~10 s

try_join! completes at once with that error, and the futures still pending are dropped unfinished: they are never polled again, their destructors run, and any code after their current .await never executes.

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

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%

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.

open as a page

In Rust, why can't a connection type's `Drop` impl await a graceful close, and how do you structure async cleanup instead?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Drop::drop(&mut self) is synchronous, so .await in it fails with E0728, and as of Rust 1.99 async drop is unstable and nightly-only. Put async cleanup in an explicit async fn close(self) the caller awaits, with Drop as a synchronous fallback.

open as a page

A hand-written Rust Future, a Delay that polls a shared flag set by a timer thread, returns Poll::Pending without touching its Context, and block_on hangs; why, and what fixes it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Returning Poll::Pending obliges the future to arrange a wake-up, and this Delay never stores cx.waker(), so nothing wakes the task and block_on never polls it again. Store a clone of the latest Waker beside the flag, under one lock, and wake it from the timer thread.

open as a page

showing 1–30 of 40