Rust Reference ยท Iterators
Iterator chain, cycle, once and repeat
Reference for Iterator::chain and cycle plus std::iter::once, repeat, repeat_n, repeat_with and empty in Rust: joining, looping and generating sequences.
chain(other) runs one iterator and then another, as if they were a single sequence. cycle() repeats an iterator forever by cloning it when it runs out. The helpers in std::iter build small iterators from scratch: once(x) yields one item, repeat(x) yields clones of x forever, repeat_n(x, n) yields n clones, repeat_with(f) calls a closure each time, and empty() yields nothing.
They are the glue for assembling sequences without allocating a temporary Vec, such as "header row, then data rows", "separator between items", or "round-robin over a short list".
use std::iter; let v: Vec<i32> = iter::once(0).chain(1..4).chain(iter::repeat(9).take(2)).collect(); // [0, 1, 2, 3, 9, 9]
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 chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where U: IntoIterator<Item = Self::Item>; fn cycle(self) -> Cycle<Self> where Self: Clone; std::iter::once<T>(value: T) -> Once<T> std::iter::repeat<T: Clone>(elt: T) -> Repeat<T> std::iter::repeat_n<T: Clone>(element: T, count: usize) -> RepeatN<T> std::iter::repeat_with<A, F: FnMut() -> A>(repeater: F) -> RepeatWith<F> std::iter::empty<T>() -> Empty<T>
| Name | Description |
|---|---|
other |
A second iterable with the same Item type. It is only started once the first is exhausted. |
value, elt, element |
The item to yield (cloned for repeat and repeat_n). |
count |
How many items repeat_n yields. |
repeater |
Closure called for each item of repeat_with. |
Returns: lazy iterators. repeat_n was stabilized in Rust 1.82; once, repeat, repeat_with and empty are older.
Usage notes
- Both sides must have the same
Item. ChainingIter<'_, i32>(items&i32) with a range (itemsi32) does not compile; add.copied()to one side. cycleclones the iterator, not the items, so the iterator must beClone.slice::iter(), ranges andchars()are;mapwith a capturing closure is only if the closure is. Cycling an empty iterator yields nothing and terminates.- Always bound
cycleandrepeatwithtake,ziportake_while, otherwise a consumer likecollectnever finishes and eats memory. repeat(x).take(n)versusrepeat_n(x, n). The second is exact-size; on older toolchains write the first. For repeating a string,"ab".repeat(3)is even simpler.onceandemptycombine well withif.(cond.then_some(x)).into_iter()orif cond { Some(x) } else { None }also work, sinceOptionis iterable.chainkeeps double-endedness when both parts are double-ended, and exact size when both are exact-size (as long as the sum fitsusize).- Intersperse is not in std. To put a separator between items use
joinon a slice or a manual loop.