# .iter() could be skipped when performing a combinator on Vector

**URL:** <https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418>\
**Category:** language design\
**Created:** [August 22, 2024, 2:03pm UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418 "2024-08-22T14:03:45Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![User12345](https://avatars.discourse-cdn.com/v4/letter/u/bcef8e/32.png) [@User12345](https://internals.rust-lang.org/u/User12345)\
**Post date:** [August 22, 2024, 2:03pm UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/1 "2024-08-22T14:03:45Z")

</div>

```rust
let numbers = vec![1, 2, 3, 4, 5];
let even_numbers: Vec<u32> = numbers.iter()
    .filter(|&n| n % 2 == 0)
    .collect();

```

Since we already know that `numbers` is a collection, we can skip calling `.iter()` while performing such intermediate operation. Hence suggested idea is:

```rust
let numbers = vec![1, 2, 3, 4, 5];
let even_numbers: Vec<u32> = numbers
    .filter(|&n| n % 2 == 0)
    .collect();

```

This approach is already implemented by other languages (JavaScript, Scala, ...), therefore we can bring such functionality to Rust.

---

<div class="post-metadata">

**Author:** ![farnz](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/farnz/32/6587_2.png) [@farnz](https://internals.rust-lang.org/u/farnz)\
**Post date:** [August 22, 2024, 2:22pm UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/2 "2024-08-22T14:22:04Z")

</div>

The challenge is getting the type system semantics for this correct; you need some set of type system rules (probably intermediated by traits) such that the compiler can desugar this the way you want it to.

For example, `nums.iter().filter(…).copied().collect()` is a nicer equivalent of:

```rust
Iterator::collect(Iterator::copied(Iterator::filter(
        <[u32]>::iter(<Vec<u32> as Deref>::deref(&nums)),
        |&n| n % 2 == 0,
    )));

```

To make this a useful proposal, you'd need to explain what the rules the compiler follows are to get from `nums.filter(…)` to `Iterator::filter(<[u32]>::iter(<Vec<u32> as Deref>::deref(&nums)), …)` - for current Rust, this is a combination of autoref and method call search that can be translated to a single [unambiguous set of function calls](https://doc.rust-lang.org/reference/expressions/call-expr.html#disambiguating-function-calls) by the compiler.

---

<div class="post-metadata">

**Author:** ![tguichaoua](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tguichaoua/32/8952_2.png) [@tguichaoua](https://internals.rust-lang.org/u/tguichaoua)\
**Post date:** [August 22, 2024, 2:33pm UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/3 "2024-08-22T14:33:51Z")

</div>

The reason why [`filter`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.filter) is implemented on the `Iterator` trait instead of the collection itself is that its implementation can be abtracted over any iterator. By doing so, we don't have to implement `filter` on all existing collection types.

Also, generaly collections have three methods to create an iterator `into_iter`, `iter` and `iter_mut` which explicitly state if we want to take the ownership of the values or borrow them mutably or not.

---

<div class="post-metadata">

**Author:** ![SkiFire13](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/skifire13/32/7579_2.png) [@SkiFire13](https://internals.rust-lang.org/u/SkiFire13)\
**Post date:** [August 22, 2024, 2:36pm UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/4 "2024-08-22T14:36:21Z")

</div>

> [@User12345](#):
>
> Since we already know that `numbers` is a collection, we can skip calling `.iter()` while performing such intermediate operation.

Why would that be the case?

- a collection is not an iterator, as it doesn't know at which point the iteration currently is

- why should `iter` be called, and not `iter_mut`, `into_iter`, `drain` or something else?

---

<div class="post-metadata">

**Author:** ![RalfJung](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ralfjung/32/2415_2.png) [@RalfJung](https://internals.rust-lang.org/u/RalfJung)\
**Post date:** [August 22, 2024, 3:06pm UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/5 "2024-08-22T15:06:48Z")

</div>

What does this have to do with unsafe code?

(You tagged this as "Unsafe Code Guidelines".)

---

<div class="post-metadata">

**Author:** ![User12345](https://avatars.discourse-cdn.com/v4/letter/u/bcef8e/32.png) [@User12345](https://internals.rust-lang.org/u/User12345)\
**Post date:** [August 22, 2024, 3:50pm UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/6 "2024-08-22T15:50:02Z")

</div>

That was unintentional. Apology. Fixed

---

<div class="post-metadata">

**Author:** ![dlight](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/dlight/32/8462_2.png) [@dlight](https://internals.rust-lang.org/u/dlight)\
**Post date:** [August 23, 2024, 9:37am UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/7 "2024-08-23T09:37:15Z")

</div>

The trouble with the `somevec.filter(..)` syntax is that it's ambiguous whether we should insert `.iter()`, `.iter_mut()` or `.into_iter()` implictly. Maybe one could look at what the closure accepts, so that

`somevec.filter(|&n| ..)` becomes `somevec.iter().filter(|&n| ..)`

`somevec.filter(|&mut n| ..)` becomes `somevec.iter_mut().filter(|&mut n| ..)`

So in practice this could work just fine I guess?

If you want to prototype this, you could write a crate with an extension trait and publish it to [crates.io](http://crates.io). People would just need to `use` your trait and then they would have a filter method on `Vec` that work like this.

---

<div class="post-metadata">

**Author:** ![Ratatouille](https://avatars.discourse-cdn.com/v4/letter/r/57b2e6/32.png) [@Ratatouille](https://internals.rust-lang.org/u/Ratatouille)\
**Post date:** [August 23, 2024, 9:49am UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/8 "2024-08-23T09:49:45Z")

</div>

But I do think that some generic iter method which abstract over the three of them would be a nice change. Assuming this is possible of course..

---

<div class="post-metadata">

**Author:** ![jjpe](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jjpe/32/9779_2.png) [@jjpe](https://internals.rust-lang.org/u/jjpe)\
**Post date:** [August 23, 2024, 10:57am UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/9 "2024-08-23T10:57:14Z")

</div>

> [@Ratatouille](#):
>
> But I do think that some generic iter method which abstract over the three of them would be a nice change.

That just raises the question: if we don't leave this as an "exercise for the reader", what would that look like, precisely?

---

<div class="post-metadata">

**Author:** ![afetisov](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/afetisov/32/8508_2.png) [@afetisov](https://internals.rust-lang.org/u/afetisov)\
**Post date:** [August 23, 2024, 1:21pm UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/10 "2024-08-23T13:21:52Z")

</div>

What could, perhaps, make more sense would be to define `filter` and `map` directly on the collection, producing a collection of the same type. I.e. drop both the `.iter()` and `.collect()` calls. If you don't need the flexibility and explicitness of `.into_iter()`, `.iter()` and `.iter_mut()`, you probably don't need the full flexibility and laziness of iterators in the first place.

In that case the signatures of methods are [easy to write](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=5a068680c89ebd00e280d217ebd567e2):

```rust
pub trait Filter
where
    Self: Sized + IntoIterator + FromIterator<<Self as IntoIterator>::Item>,
{
    fn filter(self, f: impl FnMut(&Self::Item) -> bool) -> Self {
        self.into_iter().filter(f).collect()
    }
}

impl<T> Filter for T
where
    T: Sized + IntoIterator + FromIterator<<T as IntoIterator>::Item>,
{}

pub trait Map<R>
where
    Self: Sized + IntoIterator,
{
    type Output: FromIterator<R>;
    fn map(self, f: impl FnMut(Self::Item) -> R) -> Self::Output {
        self.into_iter().map(f).collect()
    }
}

impl<T, R> Map<R> for Vec<T> {
    type Output = Vec<R>;
}

impl<K, V, R> Map<(K, R)> for BTreeMap<K, V>
where
    K: Ord + Eq,
{
    type Output = BTreeMap<K, R>;
}

```

This can be useful when the API shape requires passing around vectors and maps, rather than iterators. Of course, this isn't particularly rusty, so I don't expect such extension traits to get into stdlib.

---

<div class="post-metadata">

**Author:** ![R081n](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/r081n/32/12214_2.png) [@R081n](https://internals.rust-lang.org/u/R081n)\
**Post date:** [August 23, 2024, 1:43pm UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/11 "2024-08-23T13:43:51Z")

</div>

Also important to note is that at least for vectors the filter function already exists as retain()

---

<div class="post-metadata">

**Author:** ![curoli](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/curoli/32/11357_2.png) [@curoli](https://internals.rust-lang.org/u/curoli)\
**Post date:** [August 26, 2024, 2:15pm UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/12 "2024-08-26T14:15:16Z")

</div>

Many people would take that as an invitation to slap a series of `map` and `filter` calls on a collection, causing a bunch of intermediary collections to be created. Considered perfectly idiomatic, for example, in Scala. If this does not perform well, many conclude they need lazy collections.

---

<div class="post-metadata">

**Author:** ![bert](https://avatars.discourse-cdn.com/v4/letter/b/9e8a1a/32.png) [@bert](https://internals.rust-lang.org/u/bert)\
**Post date:** [August 28, 2024, 2:44am UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/13 "2024-08-28T02:44:30Z")

</div>

`.iter()` makes clear both the borrowing behavior and the fact that the operation is lazy and doesn't allocate (until collected). Removing it would not only not be a convenience but would be actively harmful by obscuring important details about the nature of the operation.

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [February 19, 2026, 2:44am UTC](https://internals.rust-lang.org/t/iter-could-be-skipped-when-performing-a-combinator-on-vector/21418/16 "2026-02-19T02:44:31Z")

</div>

Closed on February 19, 2026, 2:44am UTC

This topic was automatically closed 540 days after the last reply. New replies are no longer allowed.
