Rust Reference ยท Iterators
Iterator take, skip and step_by
Reference for Iterator::take, skip, step_by and nth in Rust: limiting infinite iterators, paging through items, striding, and the step_by(0) panic.
take(n) yields at most the first n items and then ends. skip(n) discards the first n items and yields the rest. step_by(k) yields the first item and then every k-th item after it. Combined, they let you cut any iterator down to a window, a page, or a sampled sequence.
take is also what makes infinite iterators usable: (0..).take(5) and repeat("x").take(3) are finite. All three are lazy adapters; nth(n) is the eager cousin that consumes n items and returns the next one.
let page: Vec<i32> = (1..=100).skip(20).take(5).collect(); // [21, 22, 23, 24, 25]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
fn take(self, n: usize) -> Take<Self>; fn skip(self, n: usize) -> Skip<Self>; fn step_by(self, step: usize) -> StepBy<Self>; fn nth(&mut self, n: usize) -> Option<Self::Item>;
| Name | Description |
|---|---|
n |
How many items to keep (take), drop (skip) or discard before returning one (nth, zero-based). |
step |
Distance between yielded items. Must not be 0. |
Returns: lazy adapters (Take, Skip, StepBy); nth returns Option<Item>, None if the iterator had n or fewer items.
Panics: step_by(0) panics immediately, at the call, not when the iterator is used. A step_by(1) is the same as the original iterator.
Usage notes
skipstill does the work. On a generic iteratorskip(n)has to callnext()ntimes. On slices, vectors and ranges the standard library jumps ahead withnth, so it is O(1). For a plain slice,&v[n..]is clearer.- Order matters.
skip(2).take(3)gives items 2, 3 and 4;take(3).skip(2)gives only item 2. takedoes not consume more than it needs. Aftertake(3)returns its third item, it does not callnext()on the source again, so the source's fourth item is still there when you useby_ref():it.by_ref().take(3)lets you read the rest later.- Size hints stay exact.
Take,SkipandStepByover exact-size iterators are exact-size, andtake/skipon double-ended ones remain double-ended. step_byon ranges is specialized and does not callnext()repeatedly:(0..1_000_000).step_by(1000)is fast.- Use
take_whilewhen the cut-off depends on the value, not the count: seetake_while. - Chunks versus pages. For fixed-size groups of a slice use
chunks(n); for arbitrary iterators combineskip/takeas above.