Rust Reference ยท Keywords and Statements
The async and await keywords
Reference for Rust async and await: async fn, async blocks, lazy futures, awaiting, async closures, why an executor is needed, and async in traits.
async turns a function or block into a state machine that implements Future. Calling an async fn does not run its body; it returns a future, and nothing happens until something polls that future. .await polls another future inside an async context and suspends the current one if the result is not ready.
The standard library defines the Future trait and the pieces for polling it, but it has no executor. Real programs use a runtime such as Tokio. In the examples below we poll futures with a tiny hand-written block_on.
async fn double(x: u32) -> u32 { x * 2 }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
async fn name(args) -> T { ... } // returns impl Future<Output = T> async { ... } // async block async move { ... } // takes ownership of captures async |x| expr // async closure expr.await // inside async context only
| Part | Description |
|---|---|
async fn |
Sugar for a function returning impl Future<Output = T>; the body runs lazily. |
.await |
Postfix operator: polls the future; yields control while it is Pending; evaluates to the Output. |
| Errors | fut.await? combines awaiting with the ? operator in async functions that return Result. |
Usage notes
- Nothing runs without a poll. A future that is dropped before being polled does no work. This is the opposite of eagerly started promises in some languages.
- You need an executor. Tokio, async-std and smol drive futures; crates are unavailable in these runnable examples, which is why they use a hand-written
block_on. .awaitonly works insideasync. Calling it in a normalfnis a compile error; use the runtime'sblock_onat the boundary.- Holding locks across
.awaitis a classic trap. Astd::sync::MutexGuardheld across an await point makes the future!Sendand can deadlock; use an async-aware mutex or end the guard's scope first. - Recursion needs boxing:
Box::pin(async move { ... })or a helper likeasync_recursion-style manual boxing. - Async in traits:
async fnin traits is stable since Rust 1.75, though returned futures are notSendunless you say so. - Cancellation is dropping: when a future is dropped at an await point, the rest of its body never runs.
- Since edition 2018
asyncandawaitare reserved keywords.
Related
move,fn,trait,dyn- Lessons: Async introduction, Futures by hand, Pin and Unpin