RsRust
IntermediateLesson 12 of 16

Iterators & Closures – Rust

Functional data processing with no runtime overhead.

Closures are anonymous functions that capture their environment: |x| x * faktor. The compiler usually infers the types and automatically chooses how to capture (reference, mutable reference, or ownership).

fn main() {
    let faktor = 3;
    let mal = |x| x * faktor;
    println!("{}", mal(5));       // 15

    let mut zaehler = 0;
    let mut inc = || zaehler += 1;
    inc();
    inc();
    println!("{zaehler}");        // 2
}

Iterators are lazy: map, filter, and friends only build a pipeline; it is not run until a *consumer* such as collect, sum, or for executes it. Even so, they are as fast as hand-written loops (“zero-cost abstraction”).

fn main() {
    let zahlen = vec![1, 2, 3, 4, 5, 6];
    let quadrate: Vec<i32> = zahlen.iter().map(|x| x * x).collect();
    let gerade: Vec<i32> = zahlen.iter().copied().filter(|x| x % 2 == 0).collect();
    let summe: i32 = zahlen.iter().sum();
    let fakultaet = (1..=5).fold(1, |acc, x| acc * x);
    println!("{:?} {:?} {} {}", quadrate, gerade, summe, fakultaet);
    // [1, 4, 9, 16, 25, 36] [2, 4, 6] 21 120

    let paare: Vec<(usize, char)> = "abc".chars().enumerate().collect();
    println!("{:?}", paare);                              // [(0, 'a'), (1, 'b'), (2, 'c')]
    println!("{}", zahlen.iter().any(|&x| x > 5));        // true
    println!("{:?}", zahlen.iter().rev().take(2).collect::<Vec<_>>());   // [6, 5]
}

You create your own iterators by implementing the Iterator trait: you only provide next, and you get all the other methods (map, filter, sum ...) for free.

struct Countdown(u32);

impl Iterator for Countdown {
    type Item = u32;
    fn next(&mut self) -> Option<u32> {
        if self.0 == 0 {
            None
        } else {
            self.0 -= 1;
            Some(self.0 + 1)
        }
    }
}

fn main() {
    let v: Vec<u32> = Countdown(3).collect();
    println!("{:?}", v);                                  // [3, 2, 1]
    println!("{}", Countdown(4).map(|x| x * 10).sum::<u32>());   // 100
}

You can return closures (impl Fn) or store them in data structures (Box<dyn Fn>). With move you force the closure to own its variables, which is mandatory with threads.

fn macher(n: i32) -> impl Fn(i32) -> i32 {
    move |x| x + n
}

fn main() {
    let plus5 = macher(5);
    println!("{}", plus5(10));   // 15
    let ops: Vec<Box<dyn Fn(i32) -> i32>> = vec![Box::new(|x| x + 1), Box::new(|x| x * x)];
    println!("{:?}", ops.iter().map(|f| f(7)).collect::<Vec<_>>());   // [8, 49]
}
TipWith iter() you get references (&T), with into_iter() ownership (T), and with iter_mut() mutable references. That explains many type errors involving &&i32 in filter closures; .copied() or patterns like |&&x| solve them.