Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Async and Await in Rust

Introduction

Asynchronous programming is a powerful paradigm that allows for non-blocking operations, making it possible to perform multiple tasks at once without waiting for each one to finish. In Rust, this is achieved using the async and await keywords, which allow you to write asynchronous code that looks like synchronous code.

Understanding Async Functions

An async function is a function that returns a value wrapped in a Future. A Future represents a value that may not be available yet. To define an async function, you simply add the async keyword before the function's declaration.

async fn fetch_data() -> String { "data".to_string() }

In the example above, fetch_data is an async function that returns a Future that resolves to a String.

Using Await

To execute an async function and wait for its result, you use the await keyword. This keyword pauses the execution of the async function until the Future is resolved.

let result = fetch_data().await;

In this example, fetch_data().await will wait for the Future returned by fetch_data to resolve before assigning its result to result.

Complete Example

Let's look at a complete example that combines everything we've discussed. This example will create an async function that simulates fetching data.

use std::time::Duration;
use tokio::time::sleep;


async fn fetch_data() -> String {
  sleep(Duration::from_secs(2)).await;
  "Fetched data".to_string()
}


#[tokio::main]
async fn main() {
  let result = fetch_data().await;
  println!("{}", result);
}

In this example:

  • The fetch_data function simulates a delay of 2 seconds before returning a string.
  • The main function is marked with #tokio::main, which allows it to run async code.
  • We await the result of fetch_data and print it out.

Conclusion

The async and await keywords in Rust provide a clean and efficient way to write asynchronous code. Understanding how to use them effectively will enable you to build responsive applications that can handle many tasks concurrently without blocking the main thread.