async - Rust (original) (raw)
Expand description
Returns a Future instead of blocking the current thread.
Use async
in front of fn
, closure
, or a block
to turn the marked code into a Future
. As such the code will not be run immediately, but will only be evaluated when the returned future is .awaited.
We have written an async book detailing async
/await
and trade-offs compared to using threads.
§Control Flow
return statements and ? operators within async
blocks do not cause a return from the parent function; rather, they cause the Future
returned by the block to return with that value.
For example, the following Rust function will return 5
, causing x
to take the ! type:
#[expect(unused_variables)]
fn example() -> i32 {
let x = {
return 5;
};
}
In contrast, the following asynchronous function assigns a Future<Output = i32>
to x
, and only returns 5
when x
is .await
ed:
async fn example() -> i32 {
let x = async {
return 5;
};
x.await
}
Code using ?
behaves similarly - it causes the async
block to return a Result without affecting the parent function.
Note that you cannot use break
or continue
from within an async
block to affect the control flow of a loop in the parent function.
Control flow in async
blocks is documented further in the async book.
§Editions
async
is a keyword from the 2018 edition onwards.
It is available for use in stable Rust from version 1.39 onwards.