liveBook · Manning

Infinite iterator

As explained in Learn Rust in a Month of Lunches

An infinite iterator is an iterator that has no end and can continue producing items indefinitely.

An infinite iterator has no end: it can keep producing items indefinitely. Rust's .cycle() repeats an iterator forever, while an open range such as 0.. never stops. section 9.1.4

Use an infinite iterator with a finite consumer such as .zip(), or limit it with .take(). The infinite side does not force the result to be infinite when another iterator or operation sets a boundary. section 9.1.4

Alternating labels

Cycling ["even", "odd"] produces labels forever, but zipping it with 0..=5 creates only six pairs: even, odd, even, odd, even, odd. section 9.1.4

fn main() {
    let even_odd_iter = ["even", "odd"].into_iter().cycle();    #1
 
    let even_odd_vec: Vec<(i32, &str)> = (0..=5)
        .zip(even_odd_iter)
        .collect();
    println!("{:?}", even_odd_vec);
}

Run the example to see an infinite cycling iterator safely paired with a finite range. section 9.1.4

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines cycle and open ranges, then demonstrates bounded consumption without examining iterator internals.
Examples
Shows alternating labels, an open character range, and skipping before taking ten characters.
What it assumes
Assumes basic iterators and consumer methods such as zip, take, and collect.
What you can do after
Apply it via Rust iterator methods to repeat values or generate unbounded ranges while keeping results finite.
How it connects
Connects iterators with cycle, ranges, zip, take, and collect.

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.