πŸ”„
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).

</div> The filter let only the even numbers slip through, and `.collect()` scooped them into a tidy list. πŸ”„
Ferris says: The {:?} in println! is a special way to print a whole list at once. Super handy for peeking at what's on the belt!
Try this! Change the filter to keep odd numbers instead by using x % 2 == 1. What list do you get?
## Quick quiz

Which helper changes each item as it goes by on the belt?

Right! .map() transforms every single item that passes through. πŸŽ‰

You learned… An iterator hands you items one at a time like a conveyor belt, and with closures you can .map, .filter, .sum, and .collect them. Next up: a brand-new world of Fancy Function Tricks awaits! πŸ¦€