How lifetimes flow through async fn, futures, spawned tasks, async traits and async closures. Blocks
marked rust,ignore need the tokio crate; the rest compile with std only (type-checking async code needs no
runtime).
Contents
- An
async fnreturns a future that borrows its arguments - Writing the desugared signature
- Spawned tasks need
'static - Borrowing without
'static: scoped work Sendand what is alive across.await- Boxed futures and
dynasync - Async functions in traits
- Async closures
- Checklist
An async fn returns a future that borrows its arguments
async fn word_count(text: &str) -> usize {
text.split_whitespace().count()
}
// is roughly
// fn word_count<'a>(text: &'a str) -> impl Future<Output = usize> + 'aThe returned future captures every input lifetime: text stays borrowed until the future completes, not
until the call returns. Consequences:
- You cannot create the future from a temporary and keep it:
let f = word_count(&String::from("a b")); f.awaitfails with E0716 (temporary dropped while borrowed). Bind theStringfirst. - A future borrowing locals is not
'static, so it cannot be passed totokio::spawn. &mut selfasync methods keepselfmutably borrowed across every.awaitinside them.
Writing the desugared signature
Sometimes you need the explicit form: to do work before the first .await (synchronously, in the caller),
or to return a future that borrows only some inputs.
use std::future::Future;
struct Client { base: String }
impl Client {
// Clones what it needs up front; the returned future borrows nothing (`'static`).
fn fetch(&self, path: &str) -> impl Future<Output = String> + 'static {
let url = format!("{}/{}", self.base, path);
async move { url }
}
// Borrows `self` for 'a; `path` is copied in, so the caller may drop its string right away.
fn fetch_with_base<'a>(&'a self, path: &str) -> impl Future<Output = usize> + 'a {
let path = path.to_owned();
async move { self.base.len() + path.len() }
}
}In edition 2024 -> impl Future captures all in-scope lifetimes by default; add + use<> (Rust 1.82+) to
promise the future borrows nothing, or + use<'a> to list exactly what it borrows.
Spawned tasks need 'static
// tokio::spawn<F>(f: F) where F: Future + Send + 'static
async fn handle(state: &AppState) { /* ... */ }
async fn bad(state: AppState) {
tokio::spawn(handle(&state)); // E0597: `state` does not live long enough
// (argument requires that `state` is borrowed for `'static`)
}
async fn good(state: std::sync::Arc<AppState>) {
let st = state.clone();
tokio::spawn(async move { handle(&st).await }); // the task owns an Arc clone
}'static here means "owns its data": owned values, Arc<T>, channels. Adding 'static bounds or
Box::leak to make references fit is almost always wrong. Fixes in order: move owned data in; share with
Arc; restructure so the work happens inside the current future (join!, select!, FuturesUnordered)
where borrowing is allowed.
Borrowing without 'static: scoped work
Concurrency inside one future can borrow freely, because everything finishes before the future does:
async fn enrich(items: &mut [Item], client: &Client) {
// join_all / FuturesUnordered / tokio::join! poll the futures in place: no 'static needed.
let lookups = items.iter().map(|it| client.lookup(&it.id));
let results = futures::future::join_all(lookups).await;
for (it, r) in items.iter_mut().zip(results) {
it.extra = r;
}
}For threads, std::thread::scope (1.63) gives the same "borrow, then join before returning" guarantee:
fn parallel_len(parts: &[String]) -> usize {
std::thread::scope(|s| {
let handles: Vec<_> = parts.iter().map(|p| s.spawn(move || p.len())).collect();
handles.into_iter().map(|h| h.join().unwrap()).sum()
})
}There is no sound "scoped spawn" for async tasks in Tokio; async-scoped-style crates rely on blocking or
unsafe guarantees. Prefer in-place concurrency or owned data.
Send and what is alive across .await
A multi-threaded runtime may resume a task on another thread at each .await, so everything alive across an
.await must be Send. The usual culprits are not lifetimes but !Send guards and pointers:
use std::sync::Mutex;
async fn tick() {}
async fn record(m: &Mutex<Vec<u32>>, v: u32) {
{
let mut g = m.lock().unwrap(); // std MutexGuard is !Send
g.push(v);
} // dropped before the await
tick().await;
}
fn assert_send<T: Send>(_: T) {}
fn check(m: &'static Mutex<Vec<u32>>) { assert_send(record(m, 1)); }Holding g across tick().await makes the future !Send ("future cannot be sent between threads safely").
Rc, RefCell borrows and &T where T: !Sync cause the same error. Use Arc, scope guards, or
tokio::sync::Mutex when a lock really must be held across an .await.
Boxed futures and dyn async
When you need a trait object or recursion, box the future and spell out its lifetime:
use std::future::Future;
use std::pin::Pin;
type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>; // same shape as futures::future::BoxFuture
fn depth<'a>(name: &'a str, n: u32) -> BoxFuture<'a, usize> {
Box::pin(async move {
if n == 0 { name.len() } else { depth(name, n - 1).await + 1 } // recursion needs the box
})
}Without + 'a, Box<dyn Future> means + 'static and the future could not borrow name.
Async functions in traits
async fn and -> impl Trait in traits are stable since Rust 1.75:
trait Store {
async fn get(&self, key: &str) -> Option<String>;
}
struct Mem(std::collections::HashMap<String, String>);
impl Store for Mem {
async fn get(&self, key: &str) -> Option<String> {
self.0.get(key).cloned()
}
}Lifetime and Send notes:
- The returned future captures
&selfandkey(all input lifetimes), like a freeasync fn. - Callers cannot require the future to be
Send(needed bytokio::spawn) with plainasync fnin a public trait; theasync_fn_in_traitlint warns about this. Options: declarefn get(&self, key: &str) -> impl Future<Output = Option<String>> + Send;in the trait, or generate aSendvariant with#[trait_variant::make(SendStore: Send)](thetrait-variantcrate). - Traits with
async fnare not dyn-compatible. Fordyn Store, returnBoxFuture<'_, T>explicitly or use theasync-traitcrate (boxes every call).
Async closures
Rust 1.85 stabilised async closures (async |x| { .. }) and the AsyncFn, AsyncFnMut, AsyncFnOnce
traits. Their main lifetime benefit: the returned future may borrow from the closure's captures and from its
arguments, which F: Fn(&str) -> Fut with a separate Fut type parameter cannot express.
async fn for_each_line<F>(text: &str, f: F)
where
F: AsyncFn(&str),
{
for line in text.lines() {
f(line).await; // the future borrows `line`: fine with AsyncFn
}
}On older compilers the workaround is F: Fn(String) -> Fut (pass owned data) or boxing:
F: for<'a> Fn(&'a str) -> BoxFuture<'a, ()>.
Checklist
| Situation | Do |
|---|---|
tokio::spawn / thread::spawn with borrowed data | move owned data or Arc clones in; never 'static bounds on references |
| Future must not borrow an argument | clone/own it before an async move block; + use<..> in edition 2024 |
| Borrowing concurrency inside one request | join!, join_all, FuturesUnordered, select! |
| "future cannot be sent between threads safely" | find the !Send value alive across .await; scope or replace it |
Recursive or dyn async | Pin<Box<dyn Future<Output = T> + Send + 'a>> |
Async trait used with tokio::spawn | -> impl Future<..> + Send in the trait or trait_variant |
| Callback that receives a reference and awaits | AsyncFn(&T) (1.85+) or owned arguments |
rust-borrow-checker-error-explainer
Explain and fix Rust borrow-checker, ownership, move and lifetime compiler errors: E0382 use of moved value, E0499 cannot borrow as mutable more than once, E0502 also borrowed as immutable, E0505, E0506, E0503, E0507 cannot move out of index/Rc/reference, E0515 return reference to local, E0597 does not live long enough, E0716 temporary value dropped while borrowed, E0373 closure may outlive (spawn needs move), E0521 borrowed data escapes, E0384, E0596, E0594, E0381, E0713, 'lifetime may not live long enough', RefCell 'already borrowed: BorrowMutError' panics. Ranks fixes from restructuring (split borrows, entry API, split_at_mut, get_disjoint_mut, mem::take, Option::take, indices, thread::scope) down to clone and Rc<RefCell>/Arc<Mutex>; never unsafe. Covers NLL limits (get-or-insert), iterator invalidation, closure captures, self-referential structs. Ships std-only Rust triage tools.
rust-cargo-workspace-designer
Design, review and fix Cargo workspaces: when to split a crate (compile time, boundaries, publishing, proc-macros), crates/* vs apps/ + crates/ layouts, virtual manifest vs root package, members/exclude/default-members, resolver 2 vs 3 (MSRV-aware, edition 2024), [workspace.package] and [workspace.dependencies] inheritance, [workspace.lints], root-only profiles (lto, codegen-units), additive features with dep: and weak ?/ syntax, feature unification pitfalls, internal path + version deps, publish = false, Cargo.lock and MSRV policy, xtask, CI with --locked, nextest, rust-cache, sccache, cargo-hack/deny/machete/udeps/semver-checks, and cargo build --timings. Ships a workspace auditor and crate-graph tool.
rust-error-handling-thiserror-anyhow-designer
Design and review Rust error handling with thiserror 2 and anyhow 1: library vs application split, typed error enums with #[from], #[source], #[error(transparent)] and #[non_exhaustive], ErrorKind patterns, context via .context()/.with_context(), bail!/ensure!, source() chains, {:#} and {:?} reports, RUST_BACKTRACE/RUST_LIB_BACKTRACE, Box<dyn Error + Send + Sync>, main -> anyhow::Result or ExitCode, unwrap/expect/panic policy, Option to Result, collecting iterators of Results, axum IntoResponse mapping, retryable errors, tracing, async Send bounds, testing with matches! and downcast_ref, no_std core::error::Error, and snafu, eyre/color-eyre, miette, error-stack.
rust-tokio-async-service-builder
Build and review production async Rust services on Tokio 1.x and axum 0.8: runtime choice (#[tokio::main] multi_thread vs current_thread, Builder), axum routing with /{id} paths, State, extractors, IntoResponse error types, axum::serve with_graceful_shutdown, tower/tower-http middleware (TraceLayer, TimeoutLayer, CorsLayer, ConcurrencyLimitLayer, RequestBodyLimitLayer), Arc<AppState>, std vs tokio Mutex, JoinSet, TaskTracker, CancellationToken, select! cancel safety, bounded mpsc, oneshot, broadcast, watch, actors, Semaphore, timeouts, retries, spawn_blocking, sqlx PgPool, reqwest Client reuse, tracing, tests with start_paused and oneshot, Dockerfile. Fixes 'future cannot be sent between threads safely', E0373, Rc or MutexGuard held across await, 'Cannot start a runtime from within a runtime', 'Path segments must not start with :'. Ships std-only Rust scanners and a compiling axum 0.8 scaffold.
rust-trait-design-reviewer
Review and design Rust traits and generic APIs: generics vs impl Trait vs dyn Trait (static vs dynamic dispatch), dyn compatibility / object safety (generic methods, Self returns, where Self: Sized, error[E0038] not dyn compatible / cannot be made into an object), associated types vs generic parameters, blanket impls, coherence and orphan rule (E0117, E0119, E0210), newtype, extension, sealed and marker traits, supertraits and trait upcasting (1.86), async fn in traits (1.75) and the Send bound problem (trait_variant, async-trait), RPITIT, GATs, From/Into/TryFrom/AsRef/Borrow, std trait checklist (Debug, Clone, PartialEq, Hash, Default, Display, Error, Send/Sync, serde feature), #[must_use], #[non_exhaustive], semver hazards, Deref abuse, builders, typestate, PhantomData, Box<dyn Error + Send + Sync>, Fn traits, mockall.
rust-unsafe-block-auditor
Audit unsafe Rust for soundness: inventory every unsafe block, unsafe fn, unsafe impl/trait, extern block and unsafe attribute, check // SAFETY: comments and # Safety docs, and classify each as sound, needs-justification or likely UB, proposing safe alternatives first. Covers the five unsafe superpowers, aliasing (Stacked/Tree Borrows), invalid values, MaybeUninit vs mem::zeroed/uninitialized, transmute, slice::from_raw_parts, Vec::set_len/from_raw_parts, get_unchecked, CString::as_ptr dangling, unsafe impl Send/Sync, Pin projection, FFI (extern "C", repr(C), C-unwind, Box::into_raw/from_raw), strict provenance, static mut and &raw, edition 2024 (unsafe extern, #[unsafe(no_mangle)], unsafe_op_in_unsafe_fn, env::set_var), Miri, sanitizers, cargo-fuzz, loom, cargo-geiger and clippy safety lints.