Closures, iterators and week 7 review
Iterators and closures are two of the tools that most change how you write Rust. With them you replace for loops with helper variables by clear chains of operations such as "take the numbers, keep the even ones, square them and add them up". Best of all, they are zero-cost abstractions: the compiler turns them into code as fast as the hand-written loop. This lesson closes week 7 and prepares the ground for the final project.
Closures
A closure is an anonymous function that you can store in a variable or pass to another function. It is written with vertical bars for the parameters: |x| x + 1. Types are usually inferred. The difference from a normal function is that a closure can capture variables from its environment, using a reference, a mutable reference or taking ownership, depending on what it does with them. With the word move in front you force it to take ownership, essential when the closure must outlive the scope where it was born, for example when sending it to another thread (week 8).
fn apply<F: Fn(i32) -> i32>(f: F, value: i32) -> i32 {
f(value)
}
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
move |x| x + n // `move`: the closure owns n
}
fn main() {
let square = |x| x * x;
println!("{}", square(7));
let factor = 3;
let triple = |x| x * factor; // captures factor by reference
println!("{}", apply(triple, 5));
let add10 = make_adder(10);
println!("{}", add10(1));
let mut counter = 0;
let mut increment = || {
counter += 1; // captures counter by mutable reference
counter
};
increment();
println!("{}", increment());
}Iterators
An iterator is anything that produces a sequence of values, one at a time, with the next() method, which returns Option: Some(value) while there are some left and None at the end. You get one with iter() (references), iter_mut() (mutable references) or into_iter() (values, consuming the collection). Iterators are lazy: building a chain of operations does nothing until something consumes it. Adapters (map, filter, enumerate, zip, take, skip, rev, chain) transform one iterator into another; consumers (collect, sum, count, min, max, fold, for_each, any, all, find) produce a final result.
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let sum_of_even_squares: i32 = numbers
.iter()
.filter(|&&n| n % 2 == 0)
.map(|n| n * n)
.sum();
println!("{sum_of_even_squares}"); // 4+16+36+64+100
let words = vec!["apple", "fig", "banana", "kiwi"];
let lengths: Vec<usize> = words.iter().map(|w| w.len()).collect();
println!("{:?}", lengths);
let long: Vec<&str> = words.iter().copied().filter(|w| w.len() > 4).collect();
println!("{:?}", long);
let total = numbers.iter().fold(0, |acc, n| acc + n);
println!("{total} {:?} {:?}", numbers.iter().max(), numbers.iter().position(|&n| n == 4));
println!("{} {}", numbers.iter().any(|&n| n > 9), numbers.iter().all(|&n| n > 1));
for (i, (w, n)) in words.iter().zip(numbers.iter()).enumerate().skip(1).take(2) {
println!("{i}: {w} {n}");
}
let mut it = numbers.iter();
println!("{:?} {:?}", it.next(), it.next());
}A very useful pattern is collect into different types: a Vec, a String, a HashMap or even a Result<Vec<_>, _>, which stops at the first error. You can also implement the Iterator trait on your own types: you only have to define next, and you get all adapters and consumers for free. The following example creates a countdown and checks the rule: an iterator is lazy until you consume it.
struct Countdown {
n: u32,
}
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.n == 0 {
None
} else {
self.n -= 1;
Some(self.n + 1)
}
}
}
fn main() {
let lazy = Countdown { n: 5 }.map(|x| x * 10); // nothing runs yet
let result: Vec<u32> = lazy.collect(); // now it does
println!("{:?}", result);
let text: String = vec!["a", "b", "c"].into_iter().collect();
println!("{text}");
let ok: Result<Vec<i32>, _> = "1,2,3".split(',').map(|s| s.parse::<i32>()).collect();
let bad: Result<Vec<i32>, _> = "1,x,3".split(',').map(|s| s.parse::<i32>()).collect();
println!("{:?} {}", ok, bad.is_err());
}Week 7 review
- Modules (mod) organize code; everything is private unless marked pub; use brings names into scope; files mirror modules; dependencies go in Cargo.toml.
- Tests are #[test] functions with assert!, assert_eq!, #[should_panic]; cargo test runs them; integration tests go in tests/.
- Closures are anonymous functions that capture their environment; iterators are lazy and combined with adapters and consumers.
fn main() {
let phrases = vec!["the quick brown fox", "jumps over", "the lazy dog"];
let total = phrases.iter().flat_map(|p| p.split_whitespace()).count();
println!("{total}");
let shouted: Vec<String> = phrases
.iter()
.flat_map(|p| p.split_whitespace())
.filter(|w| w.len() > 3)
.map(|w| w.to_uppercase())
.collect();
println!("{:?}", shouted);
let longest = phrases
.iter()
.flat_map(|p| p.split_whitespace())
.max_by_key(|w| w.len());
println!("{:?}", longest); // ties: the LAST maximum wins
}Проверьте себя
Вопрос 1 из 6What does it mean that an iterator is lazy?
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов