Ashniu123
Ashniu123

Reputation: 407

Why is there no error when I push more elements than a Vec's capacity?

I came across this potential bug:

#[derive(Debug)]
enum StackType {
    Int(i64),
    Float(f64),
    Word(String),
}

fn main() {
    let mut stack: Vec<StackType> = Vec::with_capacity(1);
    stack.push(StackType::Int(5));
    stack.push(StackType::Float(5_f64));
    stack.push(StackType::Word(String::from("ABC")));
    println!("{:?}", stack);
}

I am using Rust v1.26.0 (a77568041 2018-05-07) on Windows 10.

When I compile and run the above program, I expect an error since the capacity specified is 1 and I have used push 3 times but the output is proper:

[Int(5), Float(5.0), Word("ABC")]

Upvotes: 2

Views: 610

Answers (1)

Jorge Israel Pe&#241;a
Jorge Israel Pe&#241;a

Reputation: 38616

Vec can grow dynamically, it's similar to C++'s std::vector. The fact that you specify with_capacity simply means that it can hold that many elements without reallocating. See the documentation for Vec::with_capacity:

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.

Here's an excerpt from Vec's documentation on Capacity and Reallocation:

The capacity of a vector is the amount of space allocated for any future elements that will be added onto the vector. This is not to be confused with the length of a vector, which specifies the number of actual elements within the vector. If a vector's length exceeds its capacity, its capacity will automatically be increased, but its elements will have to be reallocated.

For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10 more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or cause reallocation to occur. However, if the vector's length is increased to 11, it will have to reallocate, which can be slow. For this reason, it is recommended to use Vec::with_capacity whenever possible to specify how big the vector is expected to get.

This is different from a fixed-length array which may not exceed the specified length.

Upvotes: 8

Related Questions