Closures capture variables from their surroundings. add_offset borrows offset, bump borrows count mutably, and a move closure takes ownership of what it captures.
Iterator adaptors chain as in Rust: map, filter, enumerate, sum and collect.
Functions accept closures through Fn, FnMut and FnOnce bounds, and return them with impl Fn(...). Box<dyn FnMut()> stores closures of different types together.
06_closures_iterators.ox
// Closures and iterator chains.
fn closures() {
let offset = 10;
let add_offset = |x: i32| x + offset; // borrows `offset`
let r = add_offset(5);
let mut count = 0;
let mut bump = || count += 1; // mutably borrows `count`
bump();
bump();
let name = String::from("regen");
let owned = move || name.len(); // takes ownership of `name`
let squares: Vec<u32> = (1..=5).map(|n| n * n).collect();
let total: u32 = squares.iter().filter(|&&n| n % 2 == 1).sum();
let labels: Vec<String> = squares
.iter()
.enumerate()
.map(|(i, n)| format!("{i}: {n}"))
.collect();
}
fn apply<F>(f: F, value: i32) -> i32
where
F: Fn(i32) -> i32,
{
f(value)
}
fn make_multiplier(factor: i32) -> impl Fn(i32) -> i32 {
move |x| x * factor
}
fn boxed_callbacks() -> Vec<Box<dyn FnMut()>> {
Vec::new()
}