Hacker News new | ask | show | jobs
by tialaramex 1582 days ago
> every method on collections like `map` or `filter`

I think you're remembering the various iterator adaptors, but they aren't methods on collections, they work on Iterators as their name implies. Somebody else explained why these methods can't all just return "Iterator" (that isn't a type) but just thought I'd mention you won't find map and filter in Rust's Vec or HashMap types, those methods live in the Iterator trait.

1 comments

`iterator.map(…)` must return a new wrapper type, because it needs to store the closure somewhere, so it returns

    struct Map { closure, original_iterator }
This fact could have been hidden by making these methods return `impl Iterator`, but it would be strictly less useful/performant in case you needed to store the iterator somewhere, because then you couldn't name the actual type, and would need to work with an abstract one.

But I do agree that the way documentation presents traits and their implementations can be overwhelming, especially the Iterator which is a pretty large trait.

> because then you couldn't name the actual type

I'm sure you know this, but `type Alias = impl Trait;` is on its way which would make naming those possible.

Although that's true, and potentially useful as a feature (not sure I want it, but pretty sure I wouldn't be angry if it was added)..

I don't think that's what your parent was talking about when they say "couldn't name the actual type".

They're saying, suppose I have a function that says it return an Iterator and I realise ah, it's not really returning an Iterator, but some subtype of Iterator - or, in Rust where subtypes don't exist, a type which merely implements Iterator. I now can't talk about the actual type being returned, because that's hidden from me, and it needn't be.

For posterity, this is Rust RFC 2515 type_alias_impl_trait.