实现说明
迭代器适配器到 collect 才执行可以归结为函数 main。
本示例的循环部分是 for v in nums.iter().filter(|n| **n % 2 == 0)。
使用要点
- 直接运行文件,输出会带上标签,比如
pipeline built, nothing ran yet、total:、even:——输出的每一行都能指回产生它的那次调用。
常见问题
运行「迭代器适配器到 collect 才执行」会打印什么?
运行文件本身,pipeline built, nothing ran yet、total:、even: 这些前缀各对应一段演示逻辑。
核心语句
let total: i32 = nums.iter().filter(|n| **n > 2).map(|n| n * 10).sum();
let pipeline = nums.iter().filter(|n| **n > 2).map(|n| n * 10);
for v in nums.iter().filter(|n| **n % 2 == 0) {
println!("even: {v}");
}
代码示例
fn main() {
let nums = vec![5, 2, 8, 1, 9, 3];
// Adapters only assemble the pipeline; no traversal has happened
let pipeline = nums.iter().filter(|n| **n > 2).map(|n| n * 10);
println!("pipeline built, nothing ran yet");
// collect is what drives the whole pipeline
let out: Vec<i32> = pipeline.collect();
println!("{out:?}");
// The same pipeline with a different driver: sum consumes the iterator straight into a total
let total: i32 = nums.iter().filter(|n| **n > 2).map(|n| n * 10).sum();
println!("total: {total}");
// A for loop consuming items one by one drives the pipeline too
for v in nums.iter().filter(|n| **n % 2 == 0) {
println!("even: {v}");
}
}