Why is pin_mut needed for iteration of async_stream?

I'm using async_stream to create a Stream, and I see the docs say I need to use pin_mut! on it before iterating. However, when I don't use pin_mut! it still works just fine.

I can't find any explanation of why or when this is needed in the docs, other than the "needed for iteration" comment in the example.

Why is this needed and why is it working for me without it?

The next method requires that the stream implements Unpin (docs). You can iterate over it fine because your stream likely already implements Unpin (is not self-referential), but some streams are self-referential and so require pinning it to the stack.

It's because async-stream uses the async/await syntax, which generates self-referential types, and self-referential types require pinning.

There are several possible reasons you might not need it. For example, maybe you used for_each instead of calling next multiple times. Another possibility is that you put it in a Box, which is another way to pin it.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.