Implement collect_with_capacity for Iter?
Hi, a simple implementation of collect_with_capacity would be helpful to reduce boilerplate, a simple way I am doing this in my projects is
trait CollectWithCapacity: Iterator {
fn collect_with_capacity<T>(self, capacity: usize) -> Vec<Self::Item>
where
Self: Sized + Iterator<Item = T>,
{
let mut vec = Vec::with_capacity(capacity);
vec.extend(self);
vec
}
}
impl<T: ?Sized> CollectWithCapacity for T where T: Iterator {}
Is there any reason something similar to this is not part of the standard library?
@PaulDotSH Is there a reason you implemented it that way? Your design is capable of feeding in a wrong capacity to with_capacity that is not guaranteed to match the size of the iterator, which is a considerable deoptimization compared to allocating with the correct capacity, which is what .collect() will do by default.
compared to allocating with the correct capacity, which is what .collect() will do by default.
Specifically the FromIterator implementation for Vec will use Iterator::size_hint.
Closing, as this information is already used. If you're not satisfied with that, I recommend checking out https://std-dev-guide.rust-lang.org/development/feature-lifecycle.html for how to proceed.