π
World 13 Β· Fancy Function Tricks
Iterators: Going Through Stuff
Imagine a conveyor belt in a factory. It hands you one item at a time, over and over, until there are none left. In Rust, that belt is called an iterator. π
One item at a time
An iterator gives you items one by one so you can do something to each. The best part is teaming it up with the closures you just learned. Here are some helpers that ride along the belt:
.map(...)β change each item as it passes by..filter(...)β only let certain items through..sum()β add everything up into one number..collect()β gather all the items into a list.
Squaring numbers on the belt
Letβs send the numbers 1 to 5 down the belt, square each one (multiply it by itself), and then add them all together.
The belt squared each number β 1, 4, 9, 16, 25 β and .sum() added them up to 55. π
Think of it like thisβ¦
Each item rolls down the conveyor belt.
.map is a machine that paints or
reshapes every item, and .sum is a bin at the end that adds them all up.
Catching only the even numbers
Now letβs use .filter with a closure to keep only the even numbers, then collect them
into a list. A number is even when dividing it by 2 leaves nothing left over (x % 2 == 0).