try_with_capacity_in

Function try_with_capacity_in 

Source
pub fn try_with_capacity_in<T, A: Allocator>(
    size: usize,
    alloc: A,
) -> Result<Vec<T, A>, TryReserveError>
Expand description

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

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

use std::alloc::System;

let mut vec = try_with_capacity_in(10, System)?;

// 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);