Skip to content

Commit

Permalink
Rollup merge of #31870 - ivan:filter-explain, r=steveklabnik
Browse files Browse the repository at this point in the history
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 :-)
  • Loading branch information
Manishearth committed Feb 24, 2016
2 parents a834cd1 + 7042c8e commit b660ca5
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/doc/book/iterators.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,10 +311,12 @@ for i in (1..100).filter(|&x| x % 2 == 0) {
```

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

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

0 comments on commit b660ca5

Please sign in to comment.