これは、なにをしたくて書いたもの?
Rustでサーバーサイドのアプリケーションを書こうと思うと、ほぼ確実に(?)非同期処理を使うようです。
少し情報をまとめておこうかなと思いまして。
実際には、tokioあたりを使いながら勉強していくことになるのかなと思います。
Rust 1.39.0で導入されたasync-await
Rustに非同期処理の構文であるasync-awaitが導入されたのは、Rust 1.39.0の時のようです。
On this coming Thursday, November 7, async-await syntax hits stable Rust, as part of the 1.39.0 release.
Async-await on stable Rust! | Rust Blog
Rust 1.39.0がいつリリースされたのかというと、2019年11月ですね。
Announcing Rust 1.39.0 | Rust Blog
先ほどのブログエントリーは、こちらからリンクされています。
async-awaitを利用するためには、関数の宣言でfnの前にasyncをつけるようです。
async fn first_function() -> u32 { .. }
こうすると、関数の戻り値がFutureになります。
そして呼び出し元はFutureに対して.awaitを書くことで結果を待つことになります。
async fn another_function() { // Create the future: let future = first_function(); // Await the future, which will execute it (and suspend // this function if we encounter a need to wait for I/O): let result: u32 = future.await; ... }
future.await?を使うことでエラーの伝播もできるようです。
似たようなasync-await構文を持つ他の言語と違い、await futureではないのが特徴です。
またFutureがゼロコストであることも特徴としているようです。
The other difference between Rust futures and futures in JS and C# is that they are based on a "poll" model, which makes them zero cost. In other languages, invoking an async function immediately creates a future and schedules it for execution: awaiting the future isn't necessary for it to execute. But this implies some overhead for each future that is created.
In contrast, in Rust, calling an async function does not do any scheduling in and of itself, which means that we can compose a complex nest of futures without incurring a per-future cost. As an end-user, though, the main thing you'll notice is that futures feel "lazy": they don't do anything until you await them.
Async-await on stable Rust! | Rust Blog
async-awaitのランタイム
Rustでasync-awaitを使う場合は、なにかしらクレートを導入する必要があるようです。つまり、Rustの標準ライブラリーだけではasync-awaitは
使えないということですね。
こちらに、探してみた非同期ランタイムとなるクレートを並べてみます。
- tokio
- async-std
- glommio
- smol
- fuchsia-async
- Embassy
よく使われているのはtokioらしく、様々なフレームワークで使われているようです。
Asynchronous Programming in Rust
rust-lang.github.ioドメインにある「Asynchronous Programming in Rust」。
Introduction - Asynchronous Programming in Rust
なぜかこのページからたどり着くことができないのですが…。
Learn Rust - Rust Programming Language
書き直し中、という事情からかもしれません。
NOTE: this guide is currently undergoing a rewrite after a long time without much work. It is work in progress, much is missing, and what exists is a bit rough.
Introduction - Asynchronous Programming in Rust
他のドキュメントはdoc.rust-lang.orgドメインですしね。
The Rust Programming Language - The Rust Programming Language
GitHub - rust-lang/async-book: Asynchronous Programming in Rust