Iterator Adaptor Chaining Pipelines

Compose map filter and take over an iterator so transformations stay lazy and nothing is allocated until the consuming collect.

RustData Integrity

Code

rustsnippet
23 lines
fn main() {
    let readings = [3, 9, 1, 7, 4, 12, 2];

    // 适配器惰性组合:collect 之前不分配任何中间集合
    let summarized: Vec<String> = readings
        .iter()
        .filter(|&&v| v > 2)
        .take(4)
        .enumerate()
        .map(|(i, v)| format!("#{}: {}", i + 1, v * 10))
        .collect();

    for line in &summarized {
        println!("{}", line);
    }

    // fold 聚合:单遍遍历求和与计数
    let (sum, count) = readings
        .iter()
        .filter(|&&v| v % 2 == 1)
        .fold((0, 0), |(s, c), &v| (s + v, c + 1));
    println!("odd sum {} over {}", sum, count);
}

Inside the snippet

Iterator Adaptor Chaining Pipelines reduces to the function main.

Repetition is confined to for line in &summarized — the rest of the file is straight-line.

Using it

The demo output is labeled (odd sum); each label names the call that printed it.

Key statements

.map(|(i, v)| format!("#{}: {}", i + 1, v * 10))
.collect();
.fold((0, 0), |(s, c), &v| (s + v, c + 1));

Interactive Tools for This Topic

FAQ

What does Iterator Adaptor Chaining Pipelines print when run?
The script runs standalone; its 1 labeled outputs include `odd sum`.