Sub topic 2
Writing async fn and async blocks
This chapter assumes you know Rust ownership and borrowing, closures and move, and the Result type. It also assumes you can add tokio with the full feature to Cargo.toml. You will learn the two ways to create a future with syntax: async fn and async blocks.
What async fn does
An async fn looks like a normal function, but calling it does not run its body. It returns a value that implements Future. The declared return type is the future's Output.
use std::time::Duration;
use tokio::time::sleep;
async fn greet(name: &str) -> String {
sleep(Duration::from_millis(100)).await;
format!("Hello, {name}!")
}
#[tokio::main]
async fn main() {
let message = greet("Ferris").await;
println!("{message}");
}greet is declared as returning String. Its real signature is closer to fn greet(name: &str) -> impl Future<Output = String> + '_. The '_ means the future borrows name, so name must stay alive until the future finishes.
What async blocks do
An async { ... } block creates an anonymous future in the middle of other code. Use it when you want a future without naming a new function. It is also how you build a future that captures local variables.
#[tokio::main]
async fn main() {
let fut = async {
println!("running");
};
println!("created");
fut.await;
}The output is created, then running. Building the block does no work. The body runs only when something awaits or polls the future. The next chapters cover that behavior in detail.
Capturing variables
An async block captures variables like a closure does. By default it borrows them. Add move to take ownership.
#[tokio::main]
async fn main() {
let name = String::from("Ferris");
let borrowed = async { println!("hi {name}") };
borrowed.await;
let owned = async move { println!("bye {name}") };
owned.await;
}The move form matters when the future must outlive the current scope. Spawned tasks need it, as a later chapter shows.
Comparing the two forms
| Form | Creates | Typical use |
|---|---|---|
| `async fn name()` | A named function that returns a future | Reusable operations |
| `async { }` | An anonymous future that borrows captures | One-off work in the current scope |
| `async move { }` | An anonymous future that owns captures | Tasks and returned futures |
Common errors
- Using
.awaitoutside async code..awaitis only valid inside anasync fn, an async block, or an async closure body. In a plainfn mainyou get error E0728. Fix it with#[tokio::main]or by moving the call into an async context. - Forgetting
.await. The compiler warns that the future is unused. The code compiles but does nothing. - Borrowing a local in a returned future. An async block that borrows a local variable cannot be returned from the function that owns it. Use
async move.
Exercise
What does let f = async { println!("x"); }; print when it executes, and what must you do to make "x" appear?
Show answer
It prints nothing. The statement only creates a future. Write f.await inside an async context, such as #[tokio::main] async fn main, to run the body and print "x".
Exercise
Why does an async block that uses a local String fail to compile when you return it from a function, and how do you fix it?
Show answer
A plain async block borrows the String, which is dropped when the function returns. Change it to async move { ... } so the future owns the String.