diff --git a/README.md b/README.md index a773857..ad256f2 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,9 @@ async fn main() { } }; - pin_mut!(s); // needed for iteration + // Stream must be pinned before iteration. It can be done with Box::pin, + // but the pin_mut macro is more efficient. See "Pinning" section. + pin_mut!(s); while let Some(value) = s.next().await { println!("got {}", value); @@ -60,7 +62,7 @@ fn zero_to_three() -> impl Stream { #[tokio::main] async fn main() { let s = zero_to_three(); - pin_mut!(s); // needed for iteration + pin_mut!(s); // Pinning is needed for iteration while let Some(value) = s.next().await { println!("got {}", value); @@ -99,7 +101,7 @@ fn double>(input: S) #[tokio::main] async fn main() { let s = double(zero_to_three()); - pin_mut!(s); // needed for iteration + pin_mut!(s); // Pinning is needed for iteration while let Some(value) = s.next().await { println!("got {}", value); @@ -135,6 +137,20 @@ fn bind_and_accept(addr: SocketAddr) } ``` +## Pinning + +If you wrap the stream in `Box::pin`, the callers won't need to pin it before iterating it. This is more convenient for the callers, but adds a cost of using dynamic dispatch. + +```rust +fn zero_to_three() -> impl Stream { + Box::pin(stream! { + for i in 0..3 { + yield i; + } + }) +} +``` + ## Implementation The `stream!` and `try_stream!` macros are implemented using proc macros.