pub trait CollectWith: Iterator {
// Provided methods
fn collect_with<T>(self, capacity: impl FnOnce(usize) -> usize) -> T
where T: ExtendWithCapacity<Self::Item>,
Self: Sized { ... }
fn collect_with_exact<T>(self, capacity: impl FnOnce(usize) -> usize) -> T
where T: ExtendWithCapacity<Self::Item>,
Self: Sized { ... }
}Expand description
Trait for collecting iterator elements with flexible capacity calculation
Provided Methods§
Sourcefn collect_with<T>(self, capacity: impl FnOnce(usize) -> usize) -> T
fn collect_with<T>(self, capacity: impl FnOnce(usize) -> usize) -> T
Collect elements using a capacity calculated from a closure
capacity- Closure that calculates capacity based on iterator size hints
§About the Final Capacity Size
For example, (0..10).collect_with::<Vec<_>>(|_size_bound| 2)
(0..10).size_hint()returns(10, Some(10)).- _size_bound is 10.
- The closure returns 2, the final capacity is
max(10, 2)= 10. - The vector is created with Vec::with_capacity(10).
§Example
use collect_with::CollectWith;
let s = [vec!["a"], vec!["b", "c", "d"]]
.into_iter()
.flatten()
.collect_with::<String>(|size| match size {
0 => 8,
n => n,
});
assert_eq!(s.len(), 4);
assert_eq!(s.capacity(), 8);The collection may allocate more capacity than calculated if needed. If you need an exact capacity size, please use collect_with_exact()
Sourcefn collect_with_exact<T>(self, capacity: impl FnOnce(usize) -> usize) -> T
fn collect_with_exact<T>(self, capacity: impl FnOnce(usize) -> usize) -> T
Collect elements using exact capacity calculated from a closure.
capacity- Closure that calculates exact capacity requirement
The collection will strictly use the calculated capacity without overallocation.
Implementors§
impl<I: Iterator> CollectWith for I
Implement CollectWith trait for Iterator