問題一覧に戻る
上級並行性
問題93: async/await基礎

async/awaitはRustで非同期プログラミングを可能にします。async関数は計算を表すFutureを返します。awaitはFutureが完了するまで実行を一時停止します。これにより同期的に見える非同期コードが書けます。Futureは遅延評価され、ポーリングされるまで実行されません。asyncコードの実行にはtokioのようなエグゼキュータが必要です。

// 非同期関数
fn hello() -> &'static str {
"Hello, async!"
}

// awaitで待機
async fn greet() {
let msg = hello().;
println!("{}", msg);
}

// Futureを返す
fn returns_future() -> impl {
async { 42 }
}

fn main() {
// Futureの作成
let future = hello();
// Note: This won't compile without executor
// let result = block_on(future);
}