Skip to content
Justice Tech School

Iterator Patterns

Common patterns: find, position, any, all, max, min_by_key, fold, flat_map and chaining. Sorting uses sort_by and sort_by_key.

Example
let words = vec!["apple", "fig", "banana"];
println!("{:?}", words.iter().max_by_key(|w| w.len()));
println!("{}", words.iter().any(|w| w.starts_with('f')));
let total_len = words.iter().fold(0, |acc, w| acc + w.len());
println!("{}", total_len);

Result

Some("banana")
true
14

Exercise

Test all items.

v.iter().(|x| *x > 0)

Quiz Test

What does fold do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.