How to use async with file IO in Rust

Use the tokio crate's fs module and await file operations to perform non-blocking file IO in Rust.

Use the tokio crate with fs module to perform non-blocking file operations by marking your function as async and awaiting the result. Add tokio to your Cargo.toml dependencies and import the fs module to read or write files without blocking the thread.

use tokio::fs::File;
use tokio::io::AsyncReadExt;

async fn read_file(path: &str) -> Result<String, std::io::Error> {
    let mut file = File::open(path).await?;
    let mut contents = String::new();
    file.read_to_string(&mut contents).await?;
    Ok(contents)
}