async/await

从高层次上看,异步 Rust 代码与“正常”的顺序代码非常类似:

use futures::executor::block_on;

async fn count_to(count: i32) {
    for i in 1..=count {
        println!("Count is: {i}!");
    }
}

async fn async_main(count: i32) {
    count_to(count).await;
}

fn main() {
    block_on(async_main(10));
}

关键点:

  • 请注意,这只是一个简单的示例,用于展示语法。其中没有长时间运行的操作或任何真正的并发!

  • 异步调用的返回类型是什么?

    • main 中使用 let future: () = async_main(10); 来查看类型。
  • The “async” keyword is syntactic sugar. The compiler replaces the return type with a future.

  • 你不能将 main 声明为异步函数,除非在编译器中加入额外的指令来告诉它如何使用返回的 future。

  • You need an executor to run async code. block_on blocks the current thread until the provided future has run to completion.

  • .await 会异步地等待另一个操作的完成。与 block_on 不同,.await 不会阻塞当前线程。

  • .await can only be used inside an async function (or block; these are introduced later).