Modern Rust just says “note: calling an async function returns a future” and hides the `Future` type.
1.1 KiB
minutes
| minutes |
|---|
| 6 |
async/await
At a high level, async Rust code looks very much like "normal" sequential code:
use futures::executor::block_on;
async fn count_to(count: i32) {
for i in 0..count {
println!("Count is: {i}!");
}
}
async fn async_main(count: i32) {
count_to(count).await;
}
fn main() {
block_on(async_main(10));
}
Key points:
-
Note that this is a simplified example to show the syntax. There is no long running operation or any real concurrency in it!
-
The "async" keyword is syntactic sugar. The compiler replaces the return type with a future.
-
You cannot make
mainasync, without additional instructions to the compiler on how to use the returned future. -
You need an executor to run async code.
block_onblocks the current thread until the provided future has run to completion. -
.awaitasynchronously waits for the completion of another operation. Unlikeblock_on,.awaitdoesn't block the current thread. -
.awaitcan only be used inside anasyncfunction (or block; these are introduced later).