实现说明
底层就是函数 report、main。
for line in report(&["deploy", "verify"]) 承担全部的逐项处理。
使用要点
- 直接运行文件,输出会带上标签,比如
constructed without consuming——输出的每一行都能指回产生它的那次调用。 main按顺序串起report;运行文件就会把这个流程跑一遍。
常见问题
运行「once_with 惰性报表头」会打印什么?
运行文件本身,constructed without consuming 这些前缀各对应一段演示逻辑。
签名一览:fn report(rows: &[&str]) -> impl Iterator<Item = String> + '_
核心语句
fn report(rows: &[&str]) -> impl Iterator<Item = String> + '_ {
// 头部行只在流被真正消费时才计算
once_with(|| format!("report with {} rows", rows.len()))
.chain(rows.iter().map(|r| format!("row: {r}")))
}
代码示例
use std::iter::once_with;
fn report(rows: &[&str]) -> impl Iterator<Item = String> + '_ {
// 头部行只在流被真正消费时才计算
once_with(|| format!("report with {} rows", rows.len()))
.chain(rows.iter().map(|r| format!("row: {r}")))
}
fn main() {
for line in report(&["deploy", "verify"]) {
println!("{line}");
}
// 构造但不消费:闭包完全不执行
let _unused = report(&["a", "b"]);
println!("constructed without consuming");
}