Rust Tutorial · Structs, Enums and Collections · Lesson 17 of 29

Rust Iterators and Closures

Process collections with iterator adapters like map, filter and sum, and write closures that capture their environment.

Create a free account to save this page, take notes and track your progress. Sign in

Closures

A closure is an anonymous function that can capture variables from its surroundings: |x| x * factor.

Iterator chains

iter() borrows items, into_iter() takes ownership, and iter_mut() borrows mutably. Adapters such as map, filter, enumerate and take are lazy; consumers such as collect, sum, count and for run them. They compile to code as fast as hand-written loops.

filter, map, collect and sum
#[derive(Debug)]
struct Order { customer: &'static str, total: f64, paid: bool }

fn main() {
    let orders = vec![
        Order { customer: "ana", total: 42.0, paid: true },
        Order { customer: "ben", total: 15.5, paid: false },
        Order { customer: "chen", total: 99.9, paid: true },
    ];
    let vat = 0.2;
    let paid_with_vat: Vec<String> = orders
        .iter()
        .filter(|o| o.paid)
        .map(|o| format!("{}: {:.2}", o.customer, o.total * (1.0 + vat)))
        .collect();
    println!("{paid_with_vat:?}");
    let revenue: f64 = orders.iter().filter(|o| o.paid).map(|o| o.total).sum();
    let biggest = orders.iter().max_by(|a, b| a.total.total_cmp(&b.total)).unwrap();
    println!("revenue {revenue:.2}, biggest order {}", biggest.customer);
}

Output

["ana: 50.40", "chen: 119.88"]
revenue 141.90, biggest order chen

Run this on your computer — see “Get Started” for setup.

Test yourself

When do iterator adapters like map and filter run?

  1. Immediately
  2. Only when a consumer such as collect or sum pulls values
  3. In a background thread
  4. At compile time
Show answer

Answer: Only when a consumer such as collect or sum pulls values

Was this page helpful?