expression

Collect a bounded number of stream items

Bound how many items the consumer accumulates. A count bound is not a byte-size or time bound, and stopping consumption may require separate producer shutdown coordination. Tokio is an external dependency; see the proposed Cargo manifest. Expected stdout (not executed): [1, 2, 3] Common mistake: Collecting a never-ending stream into memory.

Formal Syntax & Structure

rust syntaxrust
stream.take(n).collect::<Vec<_>>().await

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() {    use tokio_stream::StreamExt;    let values: Vec<_> = tokio_stream::iter(1..=100).take(3).collect().await;    println!("{values:?}");}
Rust Reference