OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Iterators and small closures

Build a readable transformation pipeline and consume it.

Lesson 20 of 30 · About 20 minutes · Beginner · English

By the end of this lesson

Build a readable transformation pipeline and consume it.

Before you start

  • Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
  • Complete lesson 19, or be comfortable explaining and running its examples.

Three words to know

Iterator
An object that produces a sequence of items.
Closure
A small function-like value that can capture its environment.
Consumer
An operation such as sum or collect that drives iteration.

1. Understand the idea

Iterator adaptors such as filter and map describe work but usually do not perform it until a consumer is used. A closure uses vertical bars to declare its parameters. Keep each stage simple enough to explain in plain language. Iterator syntax is not automatically clearer than a loop; use the version that makes validation and limits easiest to see.

2. Save, run and observe

Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.

Filter then sumRUST · save as lesson.rs
fn main() {
    let values = [1, 2, 3, 4];
    let total: i32 = values.into_iter().filter(|n| n % 2 == 0).map(|n| n * 10).sum();
    println!("total={total}");
}
What you should see · example output
total=60
Compile and run on macOS/LinuxTERMINAL · Bash or Windows PowerShell
rustc --edition=2024 lesson.rs -o lesson
./lesson

3. Explain the result

filter retains 2 and 4. map produces 20 and 40. sum consumes those results and returns 60. The type annotation tells sum which result type to build. For a pipeline reading user data, preserve and handle errors rather than silently filtering failed parses away.

YOUR TURN

A small check before you continue

What result follows if the filter keeps odd numbers instead?

Show a suggested answer

40: the values 1 and 3 become 10 and 30.

Sources and scope

Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.