Skip to content

Commit a576362

Browse files
committed
Document async block control flow in async keyword
1 parent 934880f commit a576362

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

library/std/src/keyword_docs.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2388,6 +2388,40 @@ mod while_keyword {}
23882388
///
23892389
/// We have written an [async book] detailing `async`/`await` and trade-offs compared to using threads.
23902390
///
2391+
/// ## Control Flow
2392+
/// [`return`] statements and [`?`][try operator] operators within `async` blocks do not cause
2393+
/// a return from the parent function; rather, they cause the `Future` returned by the block to
2394+
/// return with that value.
2395+
///
2396+
/// For example, the following Rust function will return `5`, assigning the `!` value to `x`, which
2397+
/// goes unused:
2398+
/// ```rust
2399+
/// #[expect(unused_variables)]
2400+
/// fn example() -> i32 {
2401+
/// let x = {
2402+
/// return 5;
2403+
/// };
2404+
/// }
2405+
/// ```
2406+
/// In contrast, the following asynchronous function assigns a `Future<Output = i32>` to `x`, and
2407+
/// only returns `5` when `x` is `.await`ed:
2408+
/// ```rust
2409+
/// async fn example() -> i32 {
2410+
/// let x = async {
2411+
/// return 5;
2412+
/// };
2413+
///
2414+
/// x.await
2415+
/// }
2416+
/// ```
2417+
/// Code using `?` behaves similarly - it causes the `async` block to return a [`Result`] without
2418+
/// affecting the parent function.
2419+
///
2420+
/// Note that you cannot use `break` or `continue` from within an `async` block to affect the
2421+
/// control flow of a loop in the parent function.
2422+
///
2423+
/// Control flow in `async` blocks is documented further in the [async book][async book blocks].
2424+
///
23912425
/// ## Editions
23922426
///
23932427
/// `async` is a keyword from the 2018 edition onwards.
@@ -2397,6 +2431,10 @@ mod while_keyword {}
23972431
/// [`Future`]: future::Future
23982432
/// [`.await`]: ../std/keyword.await.html
23992433
/// [async book]: https://rust-lang.github.io/async-book/
2434+
/// [`return`]: ../std/keyword.return.html
2435+
/// [try operator]: ../reference/expressions/operator-expr.html#r-expr.try
2436+
/// [`Result`]: result::Result
2437+
/// [async book blocks]: https://rust-lang.github.io/async-book/part-guide/more-async-await.html#async-blocks
24002438
mod async_keyword {}
24012439

24022440
#[doc(keyword = "await")]

0 commit comments

Comments
 (0)