try_with_capacity

Function try_with_capacity 

Source
pub fn try_with_capacity<T>(size: usize) -> Result<Vec<T>, TryReserveError>
Expand description

Constructs a new, empty Vec<T> with the specified capacity.

The vector will be able to hold exactly capacity elements without reallocating. If capacity is 0, the vector will not allocate.

It is important to note that although the returned vector has the capacity specified, the vector will have a zero length. For an explanation of the difference between length and capacity, see Capacity and reallocation.

ยงExamples

let mut vec = try_with_capacity(10)?;

// The vector contains no items, even though it has capacity for more
assert_eq!(vec.len(), 0);
assert_eq!(vec.capacity(), 10);

// These are all done without reallocating...
for i in 0..10 {
    vec.try_push(i)?;
}
assert_eq!(vec.len(), 10);
assert_eq!(vec.capacity(), 10);

// ...but this may make the vector reallocate
vec.try_push(11)?;
assert_eq!(vec.len(), 11);
assert!(vec.capacity() >= 11);