Skip to content

Commit b660ca5

Browse files
committed
Rollup merge of #31870 - ivan:filter-explain, r=steveklabnik
As a Rust newbie, I found the book's explanation for why the `filter` closure gets a reference very confusing, and tried to figure out why `filter` is somehow less consumptive than `map` -- but it isn't; that's controlled by `iter`/`into_iter`. I flailed around for a while until @habnabit explained it to me, and in retrospect it is quite obvious :-)
2 parents a834cd1 + 7042c8e commit b660ca5

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

src/doc/book/iterators.md

+6-4
Original file line numberDiff line numberDiff line change
@@ -311,10 +311,12 @@ for i in (1..100).filter(|&x| x % 2 == 0) {
311311
```
312312

313313
This will print all of the even numbers between one and a hundred.
314-
(Note that because `filter` doesn't consume the elements that are
315-
being iterated over, it is passed a reference to each element, and
316-
thus the filter predicate uses the `&x` pattern to extract the integer
317-
itself.)
314+
(Note that, unlike `map`, the closure passed to `filter` is passed a reference
315+
to the element instead of the element itself. The filter predicate here uses
316+
the `&x` pattern to extract the integer. The filter closure is passed a
317+
reference because it returns `true` or `false` instead of the element,
318+
so the `filter` implementation must retain ownership to put the elements
319+
into the newly constructed iterator.)
318320

319321
You can chain all three things together: start with an iterator, adapt it
320322
a few times, and then consume the result. Check it out:

0 commit comments

Comments
 (0)