← 中文资源

简体中文版本

once_with 惰性报表头

once_with 把一次性计算包装成迭代器元素:闭包在流被真正消费时才执行,构造后不消费就完全不触发,适合惰性生成报表头。

阅读英文原文

实现说明

底层就是函数 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");
}