Inspect Peeks Inside Iterator Pipelines

Watch values flow through an iterator pipeline with inspect, logging each stage without altering the stream that map and filter_map continue to consume.

RustCli Tooling

Code

rustsnippet
18 lines
fn main() {
    let orders = ["tea:2", "coffee:1", "juice:0", "mocha:4"];

    // inspect:管道中途偷看每个元素,值原样流向下游
    let total: u32 = orders
        .iter()
        .inspect(|order| println!("recv {order}"))
        .filter_map(|order| {
            let (name, count) = order.split_once(':')?;
            let count: u32 = count.parse().ok()?;
            (count > 0).then_some((name, count))
        })
        .inspect(|(name, count)| println!("valid {name} x{count}"))
        .map(|(_, count)| count)
        .sum();

    println!("total cups: {total}");
}

How the snippet works

Inspect Peeks Inside Iterator Pipelines keeps everything in the function main.

Applying it

The demo output is labeled (recv, valid, total cups:), so every printed line maps back to its originating operation.

Statements that matter

let (name, count) = order.split_once(':')?;
let count: u32 = count.parse().ok()?;
.map(|(_, count)| count)
.sum();

Interactive Tools for This Topic

FAQ

What does Inspect Peeks Inside Iterator Pipelines print when run?
No setup needed: run the file and look for labeled lines like `recv`, `valid`, `total cups:` in the output.