When I create a vector, the length and the capacity are the same. What is the difference between these methods?
fn main() {
let vec = vec![1, 2, 3, 4, 5];
println!("Length: {}", vec.len()); // Length: 5
println!("Capacity: {}", vec.capacity()); // Capacity: 5
}
len()
returns the number of elements in the vector (i.e., the vector's length). In the example below,vec
contains 5 elements, solen()
returns5
.capacity()
returns the number of elements the vector can hold (without reallocating memory). In the example below,vec
can hold105
elements, since we usereserve()
to allocate at least 100 slots in addition to the original 5 (more might be allocated in order to minimize the number of allocations).Growable vectors reserve space for future additions, hence the difference between allocated space (capacity) and actually used space (length).
This is explained in the standard library's documentation for
Vec
: