1.6 KiB
1.6 KiB
Async Programming in Rust
Asynchronous programming in Rust allows you to write concurrent code that's both fast and safe.
What is Async?
Async programming is about doing multiple things at once without blocking. Instead of waiting for one operation to complete before starting another, async code can switch between tasks.
Key Concepts
Futures
A Future represents a value that may not be available yet:
async fn fetch_data() -> String {
// Simulate async work
tokio::time::sleep(Duration::from_secs(1)).await;
"Data fetched!".to_string()
}
Async/Await
The async keyword makes a function asynchronous, and await pauses execution until a future is ready:
async fn process_data() {
let data = fetch_data().await;
println!("Got: {}", data);
}
Runtimes
Rust doesn't have a built-in async runtime. Popular choices include:
- Tokio: Full-featured runtime
- async-std: Standard library approach
- smol: Minimal runtime
Example: Concurrent HTTP Requests
use tokio::task;
async fn fetch_all() {
let task1 = task::spawn(fetch_url("https://api1.example.com"));
let task2 = task::spawn(fetch_url("https://api2.example.com"));
let task3 = task::spawn(fetch_url("https://api3.example.com"));
let (result1, result2, result3) = tokio::join!(task1, task2, task3);
}
Benefits
- Performance: Handle thousands of connections efficiently
- Resource Usage: Lower memory and CPU usage
- Scalability: Build systems that scale
Async Rust might seem complex at first, but it's worth learning for building high-performance applications!