Sub topic 1
Recap: async functions return lazy futures
This chapter reviews how async fn works. Later chapters on async closures and async methods in traits build on it.
Prerequisites
You should already know:
- Rust ownership, borrowing, and lifetimes at a basic level.
- How to write
async fnand use.await, and thatFutureis the trait behind them. - How to define traits with generics and bounds.
- That closures implement
Fn,FnMut, orFnOnce. The next chapter covers this.
The examples use Tokio. Add tokio = { version = "1", features = ["full"] } to Cargo.toml to run them.
What an async fn returns
Calling an async fn does not run its body. It returns a value that implements Future. The body runs only when something polls that future. In practice, that is usually .await inside another async context, or an executor.
async fn greet(name: &str) -> String {
println!("running greet");
format!("hello {name}")
}
#[tokio::main]
async fn main() {
let fut = greet("Ada");
println!("future created");
let text = fut.await;
println!("{text}");
}The output is:
future created
running greet
hello Ada"running greet" prints after "future created". Creating the future did no work. Dropping a future that was never awaited also does nothing, apart from the compiler warning about an unused future.
A future is a state machine. Each .await is a point where it can pause and report Pending, then resume on the next poll.
The signature is a hidden return type
The compiler rewrites an async fn into an ordinary function that returns an anonymous future type. This signature:
async fn length(text: &str) -> usize {
text.len()
}is roughly equivalent to this one:
use std::future::Future;
fn length<'a>(text: &'a str) -> impl Future<Output = usize> + 'a {
async move { text.len() }
}The type is anonymous, so you cannot write its name. You can only describe it with impl Future<Output = usize>. Later chapters rely on this desugaring, both for closures and for trait methods.
Futures capture their arguments
The + 'a in the desugared signature matters. The future stores every argument the body uses. When an argument is a reference, the future holds that reference, so the future cannot outlive the data it borrows.
async fn shout(text: &str) -> String {
text.to_uppercase()
}
#[tokio::main]
async fn main() {
let owned = String::from("quiet");
let fut = shout(&owned);
println!("{}", fut.await);
}This compiles because owned outlives fut. If you moved owned or dropped it before awaiting fut, the borrow checker would reject the code, just as it would for any other struct holding a reference.
The future is also a value you can move around. Whether it is Send depends on what it holds across .await points. A future that keeps an Rc or a MutexGuard from std::sync alive across an await is not Send, and multithreaded executors such as Tokio's spawn will refuse it. The Send bounds chapter returns to this.
Why this matters for what follows
Two consequences carry through the rest of this tutorial:
- Because the return type is a future that may borrow from the inputs, any code that calls an async function through a generic parameter must describe that future type somehow.
- Because the future's lifetime is tied to its borrows, passing a callback that returns a future raises the question of what the future may borrow from. The classic closure pattern handles this badly.
Keep the desugared form fn(...) -> impl Future<Output = T> + 'a in mind. Both async closures and async trait methods are built on it.
Exercise
In the following code, what prints and in what order? let f = greet("Ada"); println!("a"); f.await; println!("b"); where greet is an async fn that prints "g" as its first statement.
Show answer
It prints "a", then "g", then "b". Calling greet only creates the future. The body, including the "g" print, runs when f.await polls it.
Exercise
Why does an async fn that takes &str return a future that cannot outlive the string?
Show answer
The compiler desugars it to a function returning impl Future<Output = T> + 'a. The future stores the reference as part of its state, so its lifetime is bound to the borrowed data.