DeveloperBreeze

Non-Blocking Rust Code Development Tutorials, Guides & Insights

Unlock 1+ expert-curated non-blocking rust code tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your non-blocking rust code skills on DeveloperBreeze.

Implementing Async Programming in Rust: Exploring async and await

Tutorial August 27, 2024
rust

use reqwest::Error;
use tokio::task;

async fn crawl(urls: Vec<&str>) -> Result<(), Error> {
    let mut tasks = vec![];

    for url in urls {
        let task = task::spawn(async move {
            match fetch_data(url).await {
                Ok(data) => println!("Fetched data from {}: {}", url, data),
                Err(e) => eprintln!("Failed to fetch {}: {}", url, e),
            }
        });

        tasks.push(task);
    }

    for task in tasks {
        task.await.unwrap();
    }

    Ok(())
}

#[tokio::main]
async fn main() {
    let urls = vec![
        "https://example.com",
        "https://rust-lang.org",
        "https://tokio.rs",
    ];

    if let Err(e) = crawl(urls).await {
        eprintln!("Crawl failed: {}", e);
    }
}

Asynchronous programming in Rust, powered by async and await, offers a robust framework for building efficient, non-blocking applications. By understanding how to use async functions, await, futures, and combining these with Rust’s error handling, you can write high-performance code that scales well. Libraries like tokio further enhance your ability to manage concurrency, making Rust a powerful choice for modern, async applications.