typestar

Slicing a stream in Rust

take, skip and their while variants cut an iterator down without a loop.

fn main() {
    let nums: Vec<i32> = (1..=10).collect();

    let head: Vec<&i32> = nums.iter().take(3).collect();
    let tail: Vec<&i32> = nums.iter().skip(7).collect();
    println!("{:?} {:?}", head, tail);

    let rising: Vec<&i32> = nums.iter().take_while(|n| **n < 5).collect();
    println!("{:?}", rising);

    let joined: Vec<i32> = (1..3).chain(90..92).collect();
    println!("{:?}", joined);
}

How it works

  1. take stops after n items, skip drops the first n.
  2. take_while stops at the first item that fails the test.
  3. chain runs one iterator after another.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
376
Tokens
157
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 99 seconds.

Type this snippet

Step 3 of 5 in Adapters, step 3 of 14 in Iterators & closures.

← Previous Next →