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));
}

要点:

  • これは構文を示すための単純化された例であることに注意してください。長く実行されうる操作や本物の並行処理はここには含まれません。

  • 非同期の呼び出しの返り値の型は?

    • 型を知るためにmainlet future: () = async_main(10);を使ってみてください。
  • The “async” keyword is syntactic sugar. The compiler replaces the return type with a future.

  • コンパイラに対して、返されたfutureの値をその後どう扱うべきかという、追加の指示を含めない限り、mainをasyncにすることはできません。

  • 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).