Repeat With Generates Values Lazily

Generate unbounded sequences with repeat_with: every pull calls the closure once, so take() is what actually makes the stream terminate.

RustData Integrity

Code

rustsnippet
23 lines
use std::iter;

fn main() {
    // repeat_with 每次拉取都调用一次闭包(FnMut):无界生成器
    let mut next_id = 100u64;
    let ids: Vec<u64> = iter::repeat_with(|| {
        next_id += 1;
        next_id
    })
    .take(3)
    .collect();
    println!("ids: {ids:?}");

    // 不加 take 永不结束:闭包捕获的状态随调用推进
    let mut ticks = 0u32;
    let beats: Vec<String> = iter::repeat_with(|| {
        ticks += 1;
        format!("beat-{ticks}")
    })
    .take(2)
    .collect();
    println!("beats: {beats:?}");
}

How it works

Count the function main as the entire surface area of Repeat With Generates Values Lazily.

Putting it to use

Running the file prints labeled results such as ids:, beats: — each operation’s effect is visible in the output.

Core lines

next_id += 1;

Interactive Tools for This Topic

FAQ

What does Repeat With Generates Values Lazily print when run?
Running the file directly is enough — expect labeled output lines such as `ids:`, `beats:`.