TExcelTAD
Home › Rust › Rust Closures & Iterators

Rust Closures & Iterators

Closures are small anonymous functions you can store in a variable or pass to another function. Iterators are Rust's way of walking through a sequence of values one at a time. Together they let you process data in a short, expressive style — and the compiler turns that style into code as fast as a hand-written loop.

Closures

A closure is written with vertical bars around its parameters, followed by an expression or a block:

rust · try it yourself
fn main() {
    let double = |x: i32| x * 2;
    let add = |a, b| a + b;
    let shout = |word: &str| {
        let upper = word.to_uppercase();
        format!("{}!", upper)
    };

    println!("{}", double(21));
    println!("{}", add(3, 4));
    println!("{}", shout("hello"));
}
42
7
HELLO!

Type annotations are optional: the compiler infers a and b from how add is used.

Capturing the environment

The big difference between a closure and a regular fn is that a closure can use variables from the place where it was created.

rust · try it yourself
fn main() {
    let tax_rate = 0.2;
    let with_tax = |price: f64| price * (1.0 + tax_rate);
    println!("{:.2}", with_tax(50.0));

    let mut clicks = 0;
    let mut click = || {
        clicks += 1;
        println!("click #{}", clicks);
    };
    click();
    click();
    println!("total clicks: {}", clicks);

    let name = String::from("Ferris");
    let owns_name = move || format!("{} owns this string now", name);
    println!("{}", owns_name());
}
60.00
click #1
click #2
total clicks: 2
Ferris owns this string now

How a closure captures a variable depends on what it does with it:

Closure uses the variable by… Trait Example
shared reference (read only) Fn with_tax reads tax_rate
mutable reference FnMut click changes clicks (must be let mut)
value (takes ownership) FnOnce move closures that consume data

The move keyword forces the closure to take ownership of everything it captures. You will need it when a closure outlives the current function, for example when it is sent to another thread.

Passing closures to functions

Functions accept closures through the Fn, FnMut and FnOnce traits:

rust · try it yourself
fn apply_twice<F: Fn(i32) -> i32>(f: F, value: i32) -> i32 {
    f(f(value))
}

fn main() {
    let add_five = |n| n + 5;
    let square = |n| n * n;

    println!("{}", apply_twice(add_five, 1));
    println!("{}", apply_twice(square, 3));
}
11
81

Iterators

Any collection can give you an iterator. The for loop you already know uses one behind the scenes. You can also drive an iterator by hand with next(), which returns Some(item) until the sequence ends, then None.

Method Yields
.iter() &T — borrows each item
.iter_mut() &mut T — lets you modify each item
.into_iter() T — takes ownership of each item

Adapters and consumers

Iterator methods come in two kinds. Adapters such as map, filter, enumerate, rev, take and skip return a new iterator and do nothing until asked. Consumers such as collect, sum, count, max, min, find and any actually run the iterator and produce a result.

rust · try it yourself
fn main() {
    let prices = vec![12, 45, 7, 30, 99, 3];

    let cheap: Vec<i32> = prices.iter().filter(|&&p| p < 20).cloned().collect();
    let doubled: Vec<i32> = prices.iter().map(|p| p * 2).collect();
    let total: i32 = prices.iter().sum();
    let expensive = prices.iter().filter(|p| **p > 25).count();
    let first_big = prices.iter().find(|p| **p > 40);

    println!("cheap:     {:?}", cheap);
    println!("doubled:   {:?}", doubled);
    println!("total:     {}", total);
    println!("expensive: {}", expensive);
    println!("first > 40: {:?}", first_big);
    println!("max:       {:?}", prices.iter().max());
}
cheap:     [12, 7, 3]
doubled:   [24, 90, 14, 60, 198, 6]
total:     196
expensive: 3
first > 40: Some(45)
max:       Some(99)

Chaining

Because adapters return iterators, you can chain them into a pipeline. Read it top to bottom like a recipe:

rust · try it yourself
fn main() {
    let words = vec!["apple", "kiwi", "banana", "fig", "cherry", "plum"];

    let result: Vec<String> = words
        .iter()
        .enumerate()
        .filter(|(i, _)| i % 2 == 0)
        .map(|(i, w)| format!("{}:{}", i, w.to_uppercase()))
        .collect();

    println!("{:?}", result);

    let long_letters: usize = words
        .iter()
        .filter(|w| w.len() > 4)
        .map(|w| w.len())
        .sum();
    println!("letters in long words: {}", long_letters);
}
["0:APPLE", "2:BANANA", "4:CHERRY"]
letters in long words: 17

Tip: Iterators are lazy. words.iter().map(...) on its own computes nothing; work only happens when a consumer like collect() or sum() pulls values through.

Test yourself

Which keyword makes a closure take ownership of the variables it captures?

  1. own
  2. move
  3. ref
  4. static

Which of these is a consumer that actually runs an iterator?

  1. map
  2. filter
  3. enumerate
  4. sum

What does vec![1, 2, 3].iter().map(|x| x * 10).collect::<Vec<i32>>() produce?

  1. [1, 2, 3]
  2. [10, 20, 30]
  3. 60
  4. Nothing, iterators are lazy