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.