Chain Concatenates Two Iterators

chain concatenates two iterators lazily, and iter::once appends a single tail element without allocating an intermediate collection.

RustData Integrity

Code

rustsnippet
29 lines
use std::iter;

fn main() {
    let primary = ["orders", "billing"];
    let fallback = ["auth", "search"];

    // chain 把两个序列惰性接成一个(concatenate),不分配中间集合
    let all: Vec<&str> = primary.iter().chain(fallback.iter()).copied().collect();
    println!("all: {all:?}");

    // 常见组合:主体 + 兜底 + iter::once 追加单个尾部元素
    let services: Vec<String> = primary
        .iter()
        .chain(fallback.iter())
        .chain(iter::once(&"jobs"))
        .map(|name| format!("{name}.svc"))
        .collect();
    println!("services: {services:?}");

    // 链上照样可以叠加其他适配器
    let third: Vec<&str> = primary
        .iter()
        .chain(fallback.iter())
        .copied()
        .skip(2)
        .take(1)
        .collect();
    println!("third: {third:?}");
}

What the code does

Chain Concatenates Two Iterators keeps everything in the function main.

Applying it

The demo output is labeled (all:, services:, third:), so every printed line maps back to its originating operation.

Statements that matter

let all: Vec<&str> = primary.iter().chain(fallback.iter()).copied().collect();
.map(|name| format!("{name}.svc"))
.collect();
.chain(fallback.iter())
.copied()
.skip(2)
.take(1)
.collect();

Interactive Tools for This Topic

FAQ

What does Chain Concatenates Two Iterators print when run?
Run it as a complete program — the output lines carry labels such as `all:`, `services:`, `third:`.