]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0728.md
Rollup merge of #92310 - ehuss:rustdoc-ice, r=estebank
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0728.md
1 [`await`] has been used outside [`async`] function or [`async`] block.
2
3 Erroneous code example:
4
5 ```edition2018,compile_fail,E0728
6 # use std::pin::Pin;
7 # use std::future::Future;
8 # use std::task::{Context, Poll};
9 #
10 # struct WakeOnceThenComplete(bool);
11 #
12 # fn wake_and_yield_once() -> WakeOnceThenComplete {
13 #     WakeOnceThenComplete(false)
14 # }
15 #
16 # impl Future for WakeOnceThenComplete {
17 #     type Output = ();
18 #     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
19 #         if self.0 {
20 #             Poll::Ready(())
21 #         } else {
22 #             cx.waker().wake_by_ref();
23 #             self.0 = true;
24 #             Poll::Pending
25 #         }
26 #     }
27 # }
28 #
29 fn foo() {
30     wake_and_yield_once().await // `await` is used outside `async` context
31 }
32 ```
33
34 [`await`] is used to suspend the current computation until the given
35 future is ready to produce a value. So it is legal only within
36 an [`async`] context, like an `async` function or an `async` block.
37
38 ```edition2018
39 # use std::pin::Pin;
40 # use std::future::Future;
41 # use std::task::{Context, Poll};
42 #
43 # struct WakeOnceThenComplete(bool);
44 #
45 # fn wake_and_yield_once() -> WakeOnceThenComplete {
46 #     WakeOnceThenComplete(false)
47 # }
48 #
49 # impl Future for WakeOnceThenComplete {
50 #     type Output = ();
51 #     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
52 #         if self.0 {
53 #             Poll::Ready(())
54 #         } else {
55 #             cx.waker().wake_by_ref();
56 #             self.0 = true;
57 #             Poll::Pending
58 #         }
59 #     }
60 # }
61 #
62 async fn foo() {
63     wake_and_yield_once().await // `await` is used within `async` function
64 }
65
66 fn bar(x: u8) -> impl Future<Output = u8> {
67     async move {
68         wake_and_yield_once().await; // `await` is used within `async` block
69         x
70     }
71 }
72 ```
73
74 [`async`]: https://doc.rust-lang.org/std/keyword.async.html
75 [`await`]: https://doc.rust-lang.org/std/keyword.await.html