Async Rust
async marks a function that returns a Future. The body does not run until the future is polled, usually by a runtime such as Tokio.
Detailed Explanation
async fn fetch() -> Result<String, Error> looks like a function that returns a Result. It returns a future that, when polled to completion, produces that Result. Nothing inside the function runs at the call fetch(). The call builds a state machine. .await on that future, inside another async function, suspends the caller until the inner future is ready. A runtime's executor is what polls.
This is cooperative concurrency. A thousand async tasks can live on a few OS threads because a waiting socket does not hold a stack. The cost is that you must not block those threads. std::thread::sleep, std::fs::read, and std::sync::Mutex::lock across a long wait starve every other task on that worker. Use Tokio's async I/O, tokio::time::sleep, and be careful with std locks.
async is infectious in the type system. You cannot easily call an async function from a sync function without a runtime (block_on). You cannot implement a sync trait method with an async function without boxing a future or using the async_trait crate. That friction is why people keep CPU-only code sync and put async at the I/O edge.
Rust's futures are inert. There is no implicit event loop in the language. async fn main needs #[tokio::main] or equivalent to exist. Dropping a future cancels it: the state machine is dropped, destructors run, the socket is closed. That is cancellation, and it is not a thread abort.
When you write async: network servers, many idle connections, timers. When you write threads: CPU-bound work, blocking libraries you cannot replace. When you mix: spawn_blocking for the blocking call, async for the rest.
Code Examples
async fn add(a: i32, b: i32) -> i32 {
a + b
}
#[tokio::main]
async fn main() {
let sum = add(2, 40).await;
println!("{sum}"); // prints: 42
}Common Gotchas
An async function does no work until polled
`let _ = fetch();` builds a future and drops it. You must `.await` or spawn it.
Do not block inside async
`thread::sleep` on a Tokio worker holds the worker. Use `tokio::time::sleep`.
`async fn` in traits needed extra help until recently
Modern Rust can write `async fn` in traits. Older code uses `async_trait` and a boxed future.
Drop is cancel
A future dropped at `.await` will not resume. Hold it if you need the operation to finish.