|
| 1 | +# Futures |
| 2 | + |
| 3 | +What is the type of an async operation? |
| 4 | + |
| 5 | +```rust,editable,compile_fail |
| 6 | +use tokio::time; |
| 7 | +
|
| 8 | +async fn count_to(count: i32) -> i32 { |
| 9 | + for i in 1..=count { |
| 10 | + println!("Count in task: {i}!"); |
| 11 | + time::sleep(time::Duration::from_millis(5)).await; |
| 12 | + } |
| 13 | + count |
| 14 | +} |
| 15 | +
|
| 16 | +#[tokio::main] |
| 17 | +async fn main() { |
| 18 | + let _: () = count_to(13); |
| 19 | +} |
| 20 | +``` |
| 21 | + |
| 22 | +[Future](https://doc.rust-lang.org/nightly/src/core/future/future.rs.html#37) |
| 23 | +is a trait, implemented by objects that represent an operation that may not be |
| 24 | +complete yet. A future can be polled, and `poll` returns either |
| 25 | +`Poll::Ready(result)` or `Poll::Pending`. |
| 26 | + |
| 27 | +```rust |
| 28 | +use std::pin::Pin; |
| 29 | +use std::task::Context; |
| 30 | + |
| 31 | +pub trait Future { |
| 32 | + type Output; |
| 33 | + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>; |
| 34 | +} |
| 35 | + |
| 36 | +pub enum Poll<T> { |
| 37 | + Ready(T), |
| 38 | + Pending, |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +An async function returns an `impl Future`, and an async block evaluates to an |
| 43 | +`impl Future`. It's also possible (but uncommon) to implement `Future` for your |
| 44 | +own types. For example, the `JoinHandle` returned from `tokio::spawn` implements |
| 45 | +`Future` to allow joining to it. |
| 46 | + |
| 47 | +The `.await` keyword, applied to a Future, causes the current async function or |
| 48 | +block to pause until that Future is ready, and then evaluates to its output. |
| 49 | + |
| 50 | +An important difference from other languages is that a Future is inert: it does |
| 51 | +not do anything until it is polled. |
| 52 | + |
| 53 | +<details> |
| 54 | + |
| 55 | +* Run the example and look at the error message. `_: () = ..` is a common |
| 56 | + technique for getting the type of an expression. Try adding a `.await` in |
| 57 | + `main`. |
| 58 | + |
| 59 | +* The `Future` and `Poll` types are conceptually quite simple, and implemented as |
| 60 | + such in `std::task`. |
| 61 | + |
| 62 | +* We will not get to `Pin` and `Context`, as we will focus on writing async |
| 63 | + code, rather than building new async primitives. Briefly: |
| 64 | + |
| 65 | + * `Context` allows a Future to schedule itself to be polled again when an |
| 66 | + event occurs. |
| 67 | + |
| 68 | + * `Pin` ensures that the Future isn't moved in memory, so that pointers into |
| 69 | + that future remain valid. This is required to allow references to remain |
| 70 | + valid after an `.await`. |
| 71 | + |
| 72 | +</details> |
0 commit comments