What is Rust's futures `Stream` trait, and why is it consumed with `while let Some(x) = s.next().await` instead of `for`?
answer
- the async Iterator
- Poll of Option of Item
- an extension trait supplies next
- for wants IntoIterator
- next needs Unpin
basics
~10 sStream is the async counterpart of Iterator: poll_next returns Poll<Option<Item>>. A stable for loop only takes IntoIterator, so you await StreamExt::next, which yields Option<Item>, in a while let loop until it returns None.
solid answer
~40 s`Stream`, defined in `futures-core` and re-exported as `futures::stream::Stream`, has one required method, `poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>`: `Pending` means not yet, `Ready(Some(item))` is the next item and `Ready(None)` means the stream is finished. Stable std has no stream trait (`core::async_iter::AsyncIterator` is unstable) and a stable `for` loop accepts only `IntoIterator`, so code uses the `StreamExt` extension trait: `next()` returns a future resolving to `Option<Item>`, and `while let Some(x) = s.next().await` loops until `None`. `next` borrows the stream as `&mut self` and requires `Unpin`, so a stream built from async blocks, such as `stream::unfold`, must first be pinned with `std::pin::pin!` (stable since 1.68) or `Box::pin`.
code
rust · 13 linesuse futures::stream::{self, StreamExt};
fn main() {
futures::executor::block_on(async {
// A paginated listing: each step is an async block, so the stream is !Unpin.
let mut pages = stream::unfold(1u32, |page| async move {
if page > 3 { None } else { Some((format!("page {page}"), page + 1)) }
});
while let Some(p) = pages.next().await {
println!("{p}");
}
});
}go deeper
Recall that a Stream is the async version of an Iterator and that you read it with while let Some(x) = stream.next().await, importing StreamExt.
Explain poll_next's three results, why a stable for loop cannot take a Stream, and why next() demands Unpin.
Show that you recognise the cannot-be-unpinned error on a stream built from async blocks and fix it once with pin! or Box::pin before the loop.
Note that the trait still lives in futures-core rather than std, so public APIs exposing streams commit their users to that crate's version.
## Stream is the async Iterator An `Iterator` hands out items one at a time with `next(&mut self) -> Option<Item>`. A **stream** does the same for items that arrive over time: lines from a socket, rows from a cursor, pages from an API. In the Rust ecosystem the trait is `Stream`, defined in the `futures-core` crate and re-exported by `futures` as `futures::stream::Stream`: ```rust pub trait Stream { type Item; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>; fn size_hint(&self) -> (usize, Option<usize>) { (0, None) } } ``` It is modelled on `Future`, but may be polled again after producing a value. The three results of `poll_next` are: - **`Poll::Pending`**: no item yet; the stream has arranged for the task to be woken when one may be ready. - **`Poll::Ready(Some(item))`**: the next item, with more possibly to come. - **`Poll::Ready(None)`**: the stream is finished. The trait places no requirement on what a later `poll_next` does: it may panic or never resolve, though it must not cause undefined behaviour. The `fuse` adapter makes it keep returning `None`. A stream whose items are `Result<T, E>` is still ended by `None`, not by an error item; the `TryStream` and `TryStreamExt` traits add methods that short-circuit on errors. ## Why not a `for` loop On stable Rust a `for` loop desugars to `IntoIterator::into_iter` and repeated `Iterator::next` calls. `Stream` implements neither, and a stable std trait for async iteration does not exist yet: `core::async_iter::AsyncIterator` and a `for await` loop are both unstable features. So stable code awaits items by hand, through the **`StreamExt`** extension trait from `futures` (blanket-implemented for every `Stream`, and it must be in scope with `use futures::stream::StreamExt`): ```rust while let Some(page) = pages.next().await { handle(page); } ``` `next()` returns a future (`Next<'_, Self>`) that resolves to `Option<Self::Item>`; `while let` stops at the first `None`. `StreamExt` also supplies lazy adapters mirroring the iterator ones (`map`, `filter`, `then`, `take`, `fuse`) and consumers that are themselves futures (`collect`, `for_each`, `fold`). Like iterator adapters, these do nothing until polled: the trait is marked `#[must_use = "streams do nothing unless polled"]`. ## The `Unpin` requirement on `next` The signature is `fn next(&mut self) -> Next<'_, Self> where Self: Unpin`. Because `next` only borrows the stream, it cannot pin it permanently, so it insists the stream does not care about being moved. Many streams are `Unpin` (`stream::iter`, and adapters over `Unpin` streams), but a stream that stores an async block's future is not, because compiler-generated futures are `!Unpin`. `stream::unfold` with an `async move` closure is the classic case; calling `.next()` on it fails with E0277, and rustc's note suggests the fix: | stream built with | `Unpin`? | before calling `next` | |---|---|---| | `stream::iter(vec)` | yes | nothing | | `stream::iter(v).map(f)` with a plain closure | yes | nothing | | `stream::unfold(state, \|s\| async move { .. })` | no | pin it | | a `FuturesUnordered` | yes | nothing | Two ways to pin: 1. **`let mut s = std::pin::pin!(s);`**: pins on the stack; `Pin<&mut S>` is itself an `Unpin` stream, so `s.next()` compiles. `pin!` has been stable since Rust 1.68. 2. **`let mut s = Box::pin(s);`**: pins on the heap, which also works when the pinned stream must be returned or stored. Why pinning exists at all is the subject of the lesson on Pin and Unpin; for streams the practical rule is: if `next()` reports that something `cannot be unpinned`, pin the stream once, before the loop. ## Summary - `Stream::poll_next` returns `Poll<Option<Item>>`; `None` ends the stream. - The trait lives in `futures-core`, not in stable std. - Consume a stream with `while let Some(x) = s.next().await`, with `StreamExt` in scope. - `next` needs `Unpin`; pin `!Unpin` streams with `pin!` or `Box::pin`.
- Why does `StreamExt::next` require `Unpin` while `StreamExt::collect` does not?`next` only borrows the stream (`&mut self`), so it cannot keep it pinned beyond one call and must assume it may move. `collect` takes the stream by value and stores it inside the returned future, which is itself pinned while it is polled, so a `!Unpin` stream is fine there.
- What happens if you call `next()` again after a stream returned `None`?The `Stream` contract leaves that unspecified: a stream may panic, never resolve, or return something else, but it must not cause undefined behaviour. Wrap the stream with `StreamExt::fuse` when code may poll past the end; a fused stream keeps returning `None`.
- How do you turn an iterator or a sequence of async steps into a stream?`futures::stream::iter(iterable)` wraps any `IntoIterator` as an `Unpin` stream that is always ready. `futures::stream::unfold(state, |s| async move { .. })` builds a stream from async steps that return `Some((item, next_state))` or `None`, and needs pinning before `next()` because it stores an async block's future.
- A stable for loop can iterate a futures Stream directly
- Stream is a trait in the standard library's prelude
- next() takes the stream by value, so you can call it only once
- A Stream signals its end with an Err item
- Polling a stream after None is guaranteed to return None again
Assumes Rust 1.99 on edition 2024 with futures 0.3; std::pin::pin! is stable since 1.68, and std still has no stable stream trait.