---
title: "Iterators and closures in Rust"
slug: "iterators-and-closures"
description: "Write closures that capture variables and chain iterator adapters such as map and filter. See why iterators are lazy and fix a use after into_iter."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-rust/iterators-and-closures"
---

# Iterators and closures in Rust

How do you transform a collection without writing the loop yourself?

## Predict

```rust
fn main() {
    let v = vec![1, 2, 3, 4];
    let s: i32 = v.iter().filter(|x| **x % 2 == 0).map(|x| x * x).sum();
    println!("{s}");
}
```

What does this program print?

- 6
- 20
- 30

Answer: 20 — filter keeps 2 and 4, map squares them to 4 and 16, and sum adds them.

Output:

```
20
```

`filter` keeps 2 and 4, `map` squares them to 4 and 16, and `sum` adds them: 20.

## Closures

A **closure** is an anonymous function you can store in a variable or pass around: `|x| x + n`. Unlike a plain function it can **capture** variables from where it is written. By default it borrows them. Put `move` before the bars and it takes ownership instead, which you need when the closure outlives the variables. A parameter of type `impl Fn(i32) -> i32` accepts a closure.

## Capturing by reference and by move

```rust
fn apply(f: impl Fn(i32) -> i32, value: i32) -> i32 {
    f(value)
}

fn main() {
    let n = 10;
    let add_n = |x| x + n;
    println!("{}", add_n(5));
    println!("{}", apply(add_n, 1));

    let name = String::from("Ferris");
    let greet = move || format!("Hello, {name}!");
    println!("{}", greet());
}
```

Output:

```
15
11
Hello, Ferris!
```

`add_n` borrows `n`. `greet` is a `move` closure, so it owns `name`; using `name` after that line would not compile.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=17733cb62944a7a721965dc419604e17

## Lazy iterators

An iterator produces items one at a time. It is **lazy**: `map`, `filter`, `enumerate` and `zip` are **adapters** that only describe a chain. Nothing runs until a **consumer** such as `collect`, `sum`, `count` or a `for` loop pulls the items. `iter()` borrows the items, and `into_iter()` takes ownership of them.

## Iterator chains

```rust
fn main() {
    let sentence = "the quick brown fox jumped";
    let lengths = sentence
        .split_whitespace()
        .map(|w| w.len())
        .collect::<Vec<_>>();
    println!("{lengths:?}");
    for (i, word) in sentence.split_whitespace().enumerate() {
        println!("{i}: {word}");
    }
    let total = lengths.iter().fold(0, |acc, n| acc + n);
    println!("total {total}");
    let longest = sentence.split_whitespace().max_by_key(|w| w.len());
    println!("{longest:?}");
}
```

Output:

```
[3, 5, 5, 3, 6]
0: the
1: quick
2: brown
3: fox
4: jumped
total 22
Some("jumped")
```

`collect::<Vec<_>>()` runs the chain and builds a vector. `enumerate` adds the index, `fold` combines all items into one value, and `max_by_key` finds the longest word.

Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=9c804d6e6887b817ef836c1ca83b1f37

## Fix it

```rust
fn main() {
    let v = vec![1, 2, 3];
    for x in v {
        println!("{x}");
    }
    println!("{} numbers", v.len());
}
```

This program does not compile. What is the bug?

- v needs to be declared mut
- len() is not defined on Vec
- The for loop took ownership of v, so v.len() uses a moved value

Answer: The for loop took ownership of v, so v.len() uses a moved value — Loop over &v or v.iter() to borrow instead of moving.

Compiler message:

```
error[E0382]: borrow of moved value: `v`
```

Fixed:

```rust
fn main() {
    let v = vec![1, 2, 3];
    for x in &v {
        println!("{x}");
    }
    println!("{} numbers", v.len());
}
```

Output:

```
1
2
3
3 numbers
```

## Say it back

In your own words: why does nothing happen until a consumer runs?

Our sentence: An adapter like map only wraps the iterator in a new one. The work happens when a consumer asks for the next item, so without one the chain never runs.

## Mission (10 min)

From a list of words, using only iterator chains, print how many there are, the longest word and the words longer than 4 letters in upper case.

```sh
cargo new word-stats
cd word-stats
cargo run
```

## Common questions

### What is a closure in Rust?

A closure is an anonymous function written with bars, like |x| x + 1. It can capture variables from the scope around it, by reference by default or by ownership with the move keyword. You can store it in a variable or pass it to a function that takes impl Fn, for example to transform each item of a collection.

### What does lazy mean for Rust iterators?

Iterator adapters such as map and filter do no work when you call them. They only build a new iterator. The items are produced when a consumer like collect, sum, count or a for loop asks for them. So you can chain many steps and the data is walked once, item by item.

### What is the difference between iter and into_iter?

iter() borrows the collection and gives references to its items, so the collection stays usable afterwards. into_iter() takes ownership and gives the items themselves, so the collection is moved and cannot be used again. A for loop over a vector uses into_iter, and a for loop over &vector uses iter.

## Sources

- https://doc.rust-lang.org/book/ch13-01-closures.html (read 2026-12-03)
- https://doc.rust-lang.org/book/ch13-02-iterators.html (read 2026-12-03)
- https://doc.rust-lang.org/std/iter/trait.Iterator.html (read 2026-12-03)

Measured with rustc 1.100.1 (play.rust-lang.org, stable, edition 2024) on 2026-12-03.
