← 中文资源

简体中文版本

用 once 与 empty 适配管道

iter::once 把单个值升格成一行迭代器、iter::empty 提供合法的零元素占位:泛型消费端不用再写 if 分支,一条与零条走同一条管道。

阅读英文原文

实现说明

用 once 与 empty 适配管道可以归结为函数 render、main。

使用要点

  • 每一步打印都带着自己的标签:nothing:。
  • main 的演示流程是 render——跑一遍文件,这条流程从头到尾可见。

常见问题

运行「用 once 与 empty 适配管道」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 nothing: 标签标明各步骤。

主签名形如 fn render(lines: impl Iterator<Item = String>) -> String

核心语句

fn render(lines: impl Iterator<Item = String>) -> String {
    lines.map(|l| format!("| {l}")).collect::<Vec<_>>().join("\n")
}
let rows = ["deploy", "verify"].map(|r| format!("step {r}"));
let nothing: Vec<String> = iter::empty().collect();

代码示例

use std::iter;

// the pipeline consumer only asks for impl Iterator: call sites adapt one item and zero items with once/empty
fn render(lines: impl Iterator<Item = String>) -> String {
    lines.map(|l| format!("| {l}")).collect::<Vec<_>>().join("\n")
}

fn main() {
    // once: a single message rides the same pipeline
    println!("{}", render(iter::once("build ok".to_string())));

    // empty: zero messages are also a valid iterator, so the call site needs no if branch
    println!("{}", render(iter::empty()));

    // once chains a fixed header row with dynamic rows into a mini report
    let rows = ["deploy", "verify"].map(|r| format!("step {r}"));
    let report = iter::once("== report ==".to_string())
        .chain(rows)
        .collect::<Vec<_>>()
        .join("\n");
    println!("{report}");

    // empty collected into any target collection stays empty: a fallback for generic interfaces
    let nothing: Vec<String> = iter::empty().collect();
    println!("nothing: {nothing:?}");
}