Asynchronous Programming
Unlike Java, Rust supports the asynchronous programming model. There are different async runtimes for Rust, the most popular being Tokio. The other options are async-std and smol.
Here's a simple example of how to define an asynchronous function in Rust. The example relies on async-std
for the implementation of sleep
:
use std::time::Duration;
use async_std::task::sleep;
async fn format_delayed(message: &str) -> String {
sleep(Duration::from_secs(1)).await;
format!("Message: {}", message)
}
Note: The Rust
async
keyword transforms a block of code into a state machine that implements theFuture
trait. This allows for writing asynchronous code sequentially.
See also: