Rust await
Created By: chatGPT
Rust provides a powerful way to handle asynchronous programming using the
async
/await
syntax. This allows for writing more readable code when dealing with operations that might take a significant amount of time, such as network requests or file I/O. The async
keyword is used to define an asynchronous function, and await
is used to pause the execution of the function until the awaited task completes.async fn fetch_data() -> Result<String, Box<dyn std::error::Error>> {
let response = reqwest::get("https://api.example.com/data").await?;
let body = response.text().await?;
Ok(body)
}
When you call an asynchronous function, it doesn't execute immediately. Instead, it returns a future that represents the eventual result of the operation. To execute a future, you'll typically need an executor. The most common executor in the Rust ecosystem is provided by the Tokio runtime.
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let data = fetch_data().await?;
println!("Fetched data: {}", data);
Ok(())
}
In this example, the fetch_data
function performs a network request to an API and returns the response body as a string. The main function, annotated with #[tokio::main]
, serves as the entry point to run the asynchronous code. It uses .await
to wait for the result of fetch_data
. If an error occurs, it will propagate that error up to the caller.
When using await inside a function, ensure that the function is marked as async
. You also need to use an asynchronous runtime like Tokio or async-std to actually run your asynchronous code.
# Cargo.toml
[dependencies]
tokio = { version = "1", features = ["full"] }