Rust Tokio Intro
Tokio is the runtime most Rust programs use to run futures. Tokio also provides async timers, files, and network tools.
The attribute starts the runtime
#[tokio::main] is an attribute from the Tokio crate (attributes were covered in Rust Attributes). It builds the runtime, so main itself can be async:
#[tokio::main]
async fn main() {
println!("Tokio is running");
}Add Tokio to your project
One line in Cargo.toml. The "full" feature turns on every part of Tokio while you learn:
// in Cargo.toml, under [dependencies]:
tokio = { version = "1", features = ["full"] }A taste: a task and a timer
Spawn a task, let it sleep without freezing anything, and collect its answer:
let countdown = tokio::spawn(async {
tokio::time::sleep(Duration::from_millis(10)).await;
"timer task done"
});
println!("{}", countdown.await.unwrap());Example
// Cargo.toml: tokio = { version = "1", features = ["full"] }
#[tokio::main]
async fn main() {
println!("Tokio is running");
let answer = get_answer().await;
println!("answer = {}", answer);
}
async fn get_answer() -> i32 {
42
}Key points
- Use Tokio to run servers, clients, and tools that wait on many things at once
- Tokio gives you tasks, timers, channels, locks, files, and network — all async
- Rust itself ships no runtime.
- The language provides futures.
In this example, #[tokio::main] builds the runtime before main starts, so main itself can be async. The first line prints at once. Then get_answer().await pauses main until that small job finishes — here it simply returns 42 — and the answer is printed. Without a runtime, the .await would have nothing to drive it.
Note
A library like Tokio runs those futures.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Why does an async Rust program need Tokio at all?