Skip to content
Tutorials Center
My learning

Topics

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".

Rust
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

Rust chain and once

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.

Rust cycle and repeat

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

Rust
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. Chaining Iter<'_, i32> (items &i32) with a range (items i32) does not compile; add .copied() to one side.
  • cycle clones the iterator, not the items, so the iterator must be Clone. slice::iter(), ranges and chars() are; map with a capturing closure is only if the closure is. Cycling an empty iterator yields nothing and terminates.
  • Always bound cycle and repeat with take, zip or take_while, otherwise a consumer like collect never finishes and eats memory.
  • repeat(x).take(n) versus repeat_n(x, n). The second is exact-size; on older toolchains write the first. For repeating a string, "ab".repeat(3) is even simpler.
  • once and empty combine well with if. (cond.then_some(x)).into_iter() or if cond { Some(x) } else { None } also work, since Option is iterable.
  • chain keeps double-endedness when both parts are double-ended, and exact size when both are exact-size (as long as the sum fits usize).
  • Intersperse is not in std. To put a separator between items use join on a slice or a manual loop.