summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_error_codes/src/error_codes/E0728.md
blob: f4968a4f00e38f4da4ea6376faeff7c039d5f63f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
[`await`] has been used outside [`async`] function or [`async`] block.

Erroneous code example:

```edition2018,compile_fail,E0728
# use std::pin::Pin;
# use std::future::Future;
# use std::task::{Context, Poll};
#
# struct WakeOnceThenComplete(bool);
#
# fn wake_and_yield_once() -> WakeOnceThenComplete {
#     WakeOnceThenComplete(false)
# }
#
# impl Future for WakeOnceThenComplete {
#     type Output = ();
#     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
#         if self.0 {
#             Poll::Ready(())
#         } else {
#             cx.waker().wake_by_ref();
#             self.0 = true;
#             Poll::Pending
#         }
#     }
# }
#
fn foo() {
    wake_and_yield_once().await // `await` is used outside `async` context
}
```

[`await`] is used to suspend the current computation until the given
future is ready to produce a value. So it is legal only within
an [`async`] context, like an `async` function or an `async` block.

```edition2018
# use std::pin::Pin;
# use std::future::Future;
# use std::task::{Context, Poll};
#
# struct WakeOnceThenComplete(bool);
#
# fn wake_and_yield_once() -> WakeOnceThenComplete {
#     WakeOnceThenComplete(false)
# }
#
# impl Future for WakeOnceThenComplete {
#     type Output = ();
#     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
#         if self.0 {
#             Poll::Ready(())
#         } else {
#             cx.waker().wake_by_ref();
#             self.0 = true;
#             Poll::Pending
#         }
#     }
# }
#
async fn foo() {
    wake_and_yield_once().await // `await` is used within `async` function
}

fn bar(x: u8) -> impl Future<Output = u8> {
    async move {
        wake_and_yield_once().await; // `await` is used within `async` block
        x
    }
}
```

[`async`]: https://doc.rust-lang.org/std/keyword.async.html
[`await`]: https://doc.rust-lang.org/std/keyword.await.html