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
takestops after n items,skipdrops the first n.take_whilestops at the first item that fails the test.chainruns one iterator after another.
Keywords and builtins used here
Vecfni32letmain
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.
Step 3 of 5 in Adapters, step 3 of 14 in Iterators & closures.