← Back to Rust Course | Chapter 14: Closures, Iterators & Async | Lesson 6 of 6

Introduction to Tokio

Tokio is a popular helper library that actually knows how to run all those paused async tasks for you.
Syntax
rust
#[tokio::main]
async fn main() {
    let handle = tokio::spawn(async {
        // task
    });
    handle.await.unwrap();
}

Adding Tokio as a Dependency

Using Tokio starts with adding it to Cargo.toml as an external dependency, since it is not part of the Rust standard library and must be fetched from crates.io.

Example: Adding Tokio as a Dependency

bash
[dependencies]
tokio = { version = "1", features = ["full"] }

⚠️ Run this in your own terminal or Node.js environment.

The #[tokio::main] Attribute

The #[tokio::main] macro is placed above async fn main(), transforming it into a real program entry point by setting up Tokio's async runtime behind the scenes.

This snippet shows the shape of such code conceptually; it needs the tokio crate and network access to actually run.

Example: The #[tokio::main] Attribute

markup
// Conceptual shape only -- requires the tokio crate (not available offline):
//
// #[tokio::main]
// async fn main() {
//     let result = say_hello().await;
//     println!("{}", result);
// }
//
// async fn say_hello() -> String {
//     String::from("Hello from an async task")
// }

fn main() {
    println!("This shows the shape of #[tokio::main] code without running it");
    println!("Real Tokio programs need the crate fetched from crates.io");
}

What Tokio Provides

Beyond just running futures, Tokio offers async-aware networking, timers, channels, and task spawning, all designed to work efficiently together under one cooperative scheduler.

Example: What Tokio Provides

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `features`, set to `["async TCP/UDP networking", "timers and sleep", "task spawning", "channels for message passing"]`
    let features = ["async TCP/UDP networking", "timers and sleep", "task spawning", "channels for message passing"];
    // Loop over `features.iter()`, binding each item to `f`
    for f in features.iter() {
        // Print "Tokio provides: {}" to the console, substituting in `f` (with a trailing newline)
        println!("Tokio provides: {}", f);
    }
}

Why This Example Cannot Run Here

Because this course's code runner has no network access to download crates from crates.io, an actual Tokio-based program cannot be compiled or executed in this environment -- only plain standard-library Rust can run here.

Example: Why This Example Cannot Run Here

markup
// Entry point: execution of the program starts here
fn main() {
    // Print "Real async runtimes like Tokio require fetching an external crate" to the console (with a trailing newline)
    println!("Real async runtimes like Tokio require fetching an external crate");
    // Print "Without network access, only std-library-only Rust can compile and run here" to the console (with a trailing newline)
    println!("Without network access, only std-library-only Rust can compile and run here");
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Assuming Tokio is part of the Rust standard library -- it is an external crate that must be added as a dependency via Cargo.
  2. Forgetting #[tokio::main] is what transforms an async fn main() into a regular fn main() that sets up and runs the runtime.
  3. Trying to run networked or timer-based async examples without network access, which will not work in an offline sandbox like this course's code runner.
Chapter Summary
  • Tokio is a widely used asynchronous runtime crate, added as an external dependency in Cargo.toml.
  • The #[tokio::main] attribute macro turns an async fn main() into a runnable program by setting up Tokio's executor.
  • Tokio provides async-friendly versions of I/O, timers, and task spawning built around the Future trait.
  • Because Tokio must be downloaded from crates.io, it requires network access and cannot run in a fully offline sandbox.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.