How does async/await work in Rust?

Asked

Viewed 86 times

7

The idea of async/await has become common in several languages (C#, Javascript etc).

It seems that Rust recently (in the 2018 edition of Rust) adopted the idea of async/await, together with the concept of Future (which, as far as I understand it, is analogous to a Promise javascript).

I’d like to know how async/await works in Rust. If necessary, also briefly on Future.

1 answer

2

When you use async in a function in Rust:

async fn teste() {
    ...
}

is the same as saying that this function returns a Future. By "down" it is as if it:

fn teste() -> impl Future {
    ...
}

and Crate Futures allows you to use so much async how much await, to create or solve an asynchronous function and expect a result within another asynchronous function.

A Crate futures also comes with the function futures::executor::block_on which serves as an executor, for you to run its asynchronous functions.

Example:

use blocking::{block_on, unblock};
use futures_lite::*;
use std::fs;

async fn read_file() {
    let contents = unblock!(fs::read_to_string("file.txt"))?;
    println!("{}", contents);
    io::Result::Ok(())
}

fn main() {
    block_on(read_file);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.