`Vec::with_capacity` in Rust

At first, I assumed since we’ve declared the capacity upfront, it would be maximum capacity of the Vec

Turns out, since Vec is expected to shrink and grow, as needed, there is no maximum capacity for Vec

It just ensures that “sufficient” memory is allocated to the Vec, such that memory reallocation is not required.

On the other hand, if you need more that what you declared with with_capacity, you will get it, but there will need to be reallocation (of memory), so it will be inefficient.

I was surprised when the following code worked (I had expected panic when my_vec had more than declared capacity)

fn main() {
    let mut my_vector: Vec<i32> = Vec::with_capacity(1);
    println!("{:?}", my_vector);
    println!("{:?}", my_vector);

This code produced the following output

[1, 2, 3, 4]

with_capacity is useful when you know upfront your memory requirement. This avoids reallocation. It provides an efficient operation when the programmer knows what to expect.