pub trait WithCapacity: Capacity + Default {
// Required method
fn with_capacity(capacity: usize) -> Self;
}Expand description
A trait for creating an empty collection with a given, pre-allocated capacity.
If a user knows in advance a minimum bound for how much capacity they will need, they can use
the with_capacity trait to pre-allocate memory in advance. The resulting collection is
guaranteed to have at least the capacity given.
If the given capacity is zero, then no capacity should be allocated at all. The behaviour of the
Default implementation should act the same as with_capacity(0).
Creating a collection with a given capacity should take linear time and space with respect to the requested capacity. Creating a collection of zero-size types should always take constant time and space.
Required Methods§
Sourcefn with_capacity(capacity: usize) -> Self
fn with_capacity(capacity: usize) -> Self
Creates a value of the given capacity.
If a value of zero is given, this should have the same effect as calling Default::default,
and should not allocate any memory.
§Examples
use len_trait::WithCapacity;
fn check_capacity<C: WithCapacity>(zero_sized: bool) {
let default = C::default();
let with_cap = C::with_capacity(10);
if zero_sized {
assert_eq!(default.capacity(), usize::max_value());
assert_eq!(with_cap.capacity(), usize::max_value());
} else {
assert_eq!(default.capacity(), 0);
assert!(with_cap.capacity() >= 10);
}
}
check_capacity::<Vec<()>>(true);
check_capacity::<Vec<usize>>(false);
check_capacity::<String>(false);Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.