Sub topic 3
Writing async fn and async blocks
This chapter assumes you know ownership, borrowing, closures with move, and the Future trait from the previous chapter. The examples use Tokio with the full feature in Cargo.toml. They use .await and #[tokio::main] as given. Later chapters cover how they work.
What an async fn really is
An async fn looks like a normal function, but calling it does not run its body. The call returns a value that implements Future, and that value holds the arguments and the code to run later.
Both functions below have the same signature as far as callers are concerned.
use std::future::Future;
async fn add(a: u32, b: u32) -> u32 {
a + b
}
fn add_desugared(a: u32, b: u32) -> impl Future<Output = u32> {
async move { a + b }
}
#[tokio::main]
async fn main() {
println!("{}", add(1, 2).await);
println!("{}", add_desugared(3, 4).await);
}The declared return type u32 becomes the future's Output. The real return type is an anonymous type generated by the compiler. You cannot name it, so you write impl Future<Output = u32> or use generics when you need to describe it.
Async blocks
An async block is an expression that produces an anonymous future without defining a function. Use it when you want a one-off piece of asynchronous work, for example to pass to tokio::spawn.
#[tokio::main]
async fn main() {
let x = 20;
let fut = async {
x + 22
};
println!("{}", fut.await);
}The block's final expression becomes the future's output. Like an async fn, the block does nothing when you create it.
Capturing variables: async versus async move
An async block captures variables from its environment the same way a closure does. A plain async block borrows them. An async move block takes ownership.
#[tokio::main]
async fn main() {
let name = String::from("Ferris");
let borrowing = async { name.len() };
println!("{}", borrowing.await);
let owning = async move { format!("Hello, {name}") };
println!("{}", owning.await);
}Here name is still usable after the first block because that block only borrowed it. The second block moves it, so name cannot be used afterward.
This choice matters most for tokio::spawn, which requires a 'static future. A borrowing block fails to compile there because the future could outlive the borrowed variable. Add move to fix it. Later chapters cover the Send and 'static rules in full.
References in async fn parameters
When an async fn takes a reference, the returned future stores that reference. The future is therefore only valid while the borrowed data lives.
async fn shout(s: &str) -> String {
s.to_uppercase()
}
#[tokio::main]
async fn main() {
let owned = String::from("hi");
let fut = shout(&owned);
println!("{}", fut.await);
}If you tried to drop(owned) between creating fut and awaiting it, the borrow checker would reject the program. The future's type carries the lifetime of &owned, so ordinary borrowing rules apply to it.
A long-lived future is easier to manage when it owns its inputs. Taking String instead of &str removes the lifetime from the future at the cost of a possible clone.
Using ? inside async blocks
In an async fn, ? returns early from the function with the error. In an async block, ? returns early from the block, and the compiler needs to know the block's error type. It often cannot infer it, so you annotate it on the final Ok.
use std::num::ParseIntError;
#[tokio::main]
async fn main() {
let fut = async {
let n: i32 = "42".parse()?;
Ok::<i32, ParseIntError>(n * 2)
};
println!("{:?}", fut.await);
}Without the Ok::<i32, ParseIntError> form, rustc reports "type annotations needed". The same fix works when a block ends with Err(...).
Recursion
A future's size must be known at compile time. A recursive async fn would contain itself, so its size would be infinite. Since Rust 1.77 you can fix this by boxing the recursive call.
async fn countdown(n: u32) -> u32 {
if n == 0 {
0
} else {
Box::pin(countdown(n - 1)).await + 1
}
}
#[tokio::main]
async fn main() {
println!("{}", countdown(3).await);
}This prints 3. The Box::pin puts the inner future on the heap, which breaks the cycle. Before 1.77, you had to return Pin<Box<dyn Future<Output = u32>>> from a regular function instead.
Closures that return futures
There are two ways to make a closure that does async work.
- A normal closure whose body is an async block. This works on all Rust versions.
- An async closure, written
async |x| { ... }, which is stable since Rust 1.85.
#[tokio::main]
async fn main() {
let add_one = |x: u32| async move { x + 1 };
println!("{}", add_one(1).await);
println!("{}", add_one(41).await);
}The closure itself is synchronous. It returns a future each time you call it. Each call creates a separate future, so you can call it many times.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `borrowed value does not live long enough` when spawning | Plain `async` block borrows a local | Use `async move` and clone what you still need |
| `type annotations needed` on `?` in a block | Error type of the block cannot be inferred | End with `Ok::<T, E>(value)` |
| `recursion in an async fn requires boxing` | The future would contain itself | Wrap the recursive call in `Box::pin(...)` |
| `value used after move` after an `async move` block | The block took ownership | Clone before the block, or restructure |
| Nothing prints and no work happens | The future was created but never awaited | Await it, or hand it to a runtime |
Summary of the model
async fn f(args) -> Treturnsimpl Future<Output = T>.async { ... }andasync move { ... }create anonymous futures, with the same borrow-or-own rules as closures.- A future holds its arguments and captured variables, so lifetimes and moves affect the future itself.
?exits the nearest async function or block, which may need an explicit error type.
Exercise
The code below does not compile. Why, and what is the smallest change that fixes it? fn main_like() { let data = vec![1, 2, 3]; let handle = tokio::spawn(async { println!("{}", data.len()); }); // handle is awaited elsewhere }
Show answer
The plain async block borrows data, but tokio::spawn requires a 'static future, and a borrow of a local cannot satisfy that. Change async to async move, so the block owns data. If you also need data after spawning, clone it first and move the clone into the block.