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.
-
コンパイラに対して、返された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 anasync
function (or block; these are introduced later).